按钮仅在Google Apps脚本中触发一次

时间:2013-05-14 05:06:06

标签: google-apps-script

我试图让一个按钮不止一次(即多次点击),但它似乎无法正常工作。任何帮助将不胜感激。从理论上讲,它应该多次点火,但只有在我在日志中检查时才会触发一次

function a 
{
...
 var addcolumnspanel = app.createHorizontalPanel().setId("addcolumnspanel");
  var addbuttonhandler = app.createServerHandler("addcolumn");
  var addbutton = app.createButton().setId("btnaddcolumn").setText("Add another column").addClickHandler(addbuttonhandler);  

...
return app;
}

function addcolumn()
{
...//Do some stuff
return app;
}

这是一个更精确的代码示例

//set global var
var counter = 1; 
var ss = SpreadsheetApp.getActiveSpreadsheet();
//Set up the Menu bar 
function onOpen() {
//  Logger.clear();
  var menuEntries = [ {name: "demo", functionName: "myFunction"}];
  ss.addMenu("Demo", menuEntries);

}

function myFunction() {

  var myapp = UiApp.createApplication().setHeight(430).setWidth(800);;
  var button = myapp.createButton("Clicky");
  var myhandler = myapp.createServerHandler("secondfunction");
  var myhandler = button.addClickHandler(myhandler)
  myapp.add(button);
  ss.show(myapp);
}

function secondfunction()
{
  counter++;
   Logger.log(counter);

}

1 个答案:

答案 0 :(得分:0)

行。问题在于计数器变量。您不能在Apps脚本中使用全局变量。有关详细信息,请参阅this answer。您可以使用ScriptProperties或CacheService作为替代方案。

var ss = SpreadsheetApp.getActiveSpreadsheet();
//Set up the Menu bar 
function onOpen() {
//  Logger.clear();
  var menuEntries = [ {name: "demo", functionName: "myFunction"}];
  ss.addMenu("Demo", menuEntries);
  // Store your counter in CacheService as a string.
  CacheService.getPrivateCache().put('counter','1',3600); 
}

function myFunction() {

  var myapp = UiApp.createApplication().setHeight(430).setWidth(800);;
  var button = myapp.createButton("Clicky");
  var myhandler = myapp.createServerHandler("secondfunction");
  var myhandler = button.addClickHandler(myhandler)
  myapp.add(button);
  ss.show(myapp);
}

function secondfunction()
{
   var cache = CacheService.getPrivateCache();
   var counter = parseInt(cache.get('counter'));
   counter ++; 
   cache.put('counter', counter.toString());
   Logger.log(counter);

}