using and modifying global variables within handle

2019-01-28 09:11发布

问题:

Hello everyone out there,

I can use global variables within a handler function, however I cannot modify them "globally" within than function.

In code below, after the first click it will show the number 1001 (the handler reads, increments and shows the right result). But, any further clicks will always show 1001, so the handler keeps reading the original globalVar value: it doesn't get modified as I was expecting.

Anything I can do to fix this?

var globalVar = 1000;

function testingGlobals() {
  var app = UiApp.createApplication();
  var doc = SpreadsheetApp.getActiveSpreadsheet();
  var panel = app.createVerticalPanel().setId('panel');
  app.add(panel);
  panel.add(app.createButton(globalVar).setId("globalVar").addClickHandler(app.createServerHandler("chgGlobal").addCallbackElement(panel)));
  doc.show(app)
}

function chgGlobal(e) {
  var app = UiApp.createApplication();
  globalVar++;
  app.getElementById("globalVar").setText(globalVar);
  return app;
}

回答1:

You can not increment Global Variables this way, as every time a handler executes, Global variable is initialized and then manipulated. You can use hidden formfields to hold the a variable which you can change in handler, and it will be persistent as long as the app is open.

e.g

function testingGlobals() {
  var app = UiApp.createApplication();
  var doc = SpreadsheetApp.getActiveSpreadsheet();
  var panel = app.createVerticalPanel().setId('panel');
  var myVar = app.createHidden().setValue('0').setName('myVar').setId('myVar');
  panel.add(myVar);
  app.add(panel);
  panel.add(app.createButton('0').setId("globalVar").addClickHandler(app.createServerHandler("chgGlobal").addCallbackElement(panel)));
  doc.show(app)
}

function chgGlobal(e) {
  var app = UiApp.createApplication();
  gloabalVar = parseInt(e.parameter.myVar);
  gloabalVar ++;
  app.getElementById('myVar').setValue(gloabalVar.toString());
  app.getElementById("globalVar").setText(gloabalVar);
  return app;
}


回答2:

You can persist data in CacheService (fast but not guaranteed) or ScriptProperties or ScriptDb (a little slower, but persisted) instead of global properties. ScriptDb in particular can hold objects without needing to use strings to store them.