Gas: How To Change A Global Variable Value And Preserve Its Changed Value When Using The Variable In A Handler Function?
Solution 1:
No theres no such option. You have to use scriptProperties or scriptDb. A global vsriable goes out of scope once your function finishes. Each outside script call starts from zero.
Solution 2:
Each separate execution of a script is done in a new execution instance. Any variables defined outside of a block of code (aka "global" variables) are therefore unique for that instance. When a trigger function is invoked by an event, it runs in its own instance, and any global values it sets are visible only to that instance; another function that is invoked by a spreadsheet or document UI, for example, would have its very own version of that non-scoped object (global).
Definition and retrieval of targetDocId
would be a good application of the Cache Service.
function get_targetDocId () {
var cache = CacheService.getPublicCache();
var cached = cache.get("targetDocId");
if (cached != null) {
return cached;
}
var target = createDuplicateDocument(template, docName); /// Need to add handling for pre-existing documentvar link = target.getUrl();
var contents = target.getId();
cache.put("targetDocId", contents, 1500); // cache for 25 minutesreturn contents;
}
Now instead of trying to use a global variable, just call this function:
...
var targetDoc = DocumentApp.openById(get_targetDocId());
...
Cache Service is one example of persistent storage available for Google Apps Script. The Properties Service was introduced after this answer was written, and is a much lighter-weight way to persist "global" variables between execution instances.
Observation: it appears that you're using a global (static) for tempate
and docName
, since there are no parameters for generatePersonDatasheet()
. You could simply generate the targetDocId on the fly.
Bug: As it is written, get_targetDocId()
will create a new copy of docName
every time it needs to refresh the cache (15 mins). You should add handling for the possibility of a pre-existing file. (This is true of your existing onOpen()
as well.)
Post a Comment for "Gas: How To Change A Global Variable Value And Preserve Its Changed Value When Using The Variable In A Handler Function?"