如何在扩展spreadheet的Google脚本上的按钮事件处理程序中传递数据

How to pass data in a button event handler on a Google script extending a spreadheet?

本文关键字:程序 事件处理 数据 按钮 脚本 扩展 spreadheet Google      更新时间:2023-09-26

扩展Google电子表格,我运行了一个脚本,在侧边栏中显示一些数据。在底部,我想添加一个按钮来邮寄数据。

然而,我不知道如何将数据从按钮传递到处理程序:

  1. 不可能将数据传递到事件调用中
  2. 没有办法从事件信息中获取按钮对象,我只能获取ID,如果我不能访问uiInstance(在处理程序函数之外创建),这是没有用的

那么诀窍是什么呢?

在将回调元素分配给按钮之前,您必须向服务器处理程序添加一个回调元素(可能是一个包含所有所需内容的面板)。例如:

function myFunction() {
  var app = UiApp.createApplication();
  var panel = app.createVerticalPanel();
  panel.setId('myPanel').add(
    app.createTextBox().setName('boxExample')).add(
    app.createListBox().setName('listExample').addItem('A').addItem('B'));
  //                                                       ↓↓ this is what you need ↓↓
  var handler = app.createServerHandler('callbackFunction').addCallbackElement(panel);
  var btn = app.createButton(btn, handler);
  app.add(panel.add(btn));
  //show app...
}
function callbackFunction(e) {
  var app = UiApp.getActiveApplication();
  app.getElementById('myPanel').add(
    app.createLabel(e.parameter.boxExample)).add(
    app.createLabel(e.parameter['listExample']));
  return app;
}

使用属性服务

我发现(我不知道是怎么做到的)谷歌脚本提供了一个名为属性服务的数据存储服务。

假设,在这种情况下,数据仅供用户使用,我需要首先将数据存储为:

var userProperties = PropertiesService.getUserProperties()
userProperties.setProperty("myKey", "myValue")
// Note myValue will be a string, so to store an array, 
// you'd need JSON.stringify(myArray)

然后,当调用按钮处理程序时,脚本可以很容易地检索数据:

var userProperties = PropertiesService.getUserProperties()
var myValue = userProperties.getProperty("myKey")

使用隐藏小工具

另一种选择似乎是使用"隐藏"小部件。
 function doGet() {
   var app = UiApp.createApplication();
   // Note that the name "appState" for callbacks, and the id "hidden" for
   // getting a reference to the widget, are not required to be the same.
   var hidden = app.createHidden("appState", "0").setId("hidden");
   app.add(hidden);
   var handler = app.createServerHandler("click").addCallbackElement(hidden);
   app.add(app.createButton("click me!", handler));
   app.add(app.createLabel("clicked 0 times").setId("label"));
   return app;
 }
 function click(eventInfo) {
   var app = UiApp.createApplication();
   // We have the value of the hidden field because it was a callback element.
   var numClicks = Number(eventInfo.parameter.appState);
   numClicks++;
   // Just store the number as a string. We could actually store arbitrarily complex data
   // here using JSON.stringify() to turn a JavaScript object into a string to store, and
   // JSON.parse() to turn the string back into an object.
   app.getElementById("hidden").setValue(String(numClicks));
   app.getElementById("label").setText("clicked " + numClicks + " times");
   return app;
 }

(来自链接参考的代码)