Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
979 views
in Technique[技术] by (71.8m points)

google apps script - using and modifying global variables within handler functions

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...