Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
981 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...