我的脚本中有这个全局变量:
var targetDocId = 'No doc ID informed yet';
我试图在我的主要功能内更改此全局变量的值:
function generatePersonDatasheet() {
var target = createDuplicateDocument(template, docName);
var link = target.getUrl();
targetDocId = target.getId(); // <-------- HERE
if (theses == 1){
Logger.log("going to showList() ");
return showList();
}
showURL(docName, link);
}
之后,我尝试在处理程序函数中访问已更改的全局变量值:
function submit(e){
var numberOfItems = Number(e.parameter.checkbox_total);
var thesesArrays = [];
for(var i = 0; i < numberOfItems; i++){
if(e.parameter['checkbox_isChecked_'+i] == 'true'){
thesesArrays.push(fact_list[i]);
}
}
for (var i = 0; i < thesesArrays.length; i++){
var thesesId = thesesArrays[i][2];
var thesesType = thesesArrays[i][1];
importTheses(targetDocId, thesesId, thesesType); // <-----HERE
}
return UiApp.getActiveApplication().close();
}
function importTheses(targetDocId, thesesId, thesesType) {
var targetDoc = DocumentApp.openById(targetDocId);
var targetDocParagraphs = targetDoc.getParagraphs();
var targetDocElements = targetDocParagraphs.getNumChildren();
var thesesDoc = DocumentApp.openById(thesesId);
var thesesParagraphs = thesesDoc.getParagraphs();
var thesesElements = thesesDoc.getNumChildren();
var eltargetDoc=[];
var elTheses=[];
for( var j = 0; j < targetDocElements; ++j ) {
var targetDocElement = targetDoc.getChild(j);
eltargetDoc[j]=targetDocElement.getText();
if(el[j]== thesesType){
for( var k = 0; k < thesesParagraphs-1; ++k ) {
var thesesElement = thesesDoc.getChild(k);
elTheses[k] = thesesDoc.getText();
targetDoc.insertParagraph(j, elTheses[k]);
}
}
}
}
但是,只要我尝试更改targetDocId
,当将其用作参数时,importTheses(targetDocId, thesesId, thesesType);
它仍然具有“尚未通知文档ID”的值,即使我更改了它,就好像程序是从头开始运行的一样。是这种“重置为原始值”行为的替代方法吗?还是我必须使用scriptDB或ScriptProperties来存储全局变量的更改后的值?
脚本的每个单独执行都在新的执行实例中完成。因此,在代码块外部定义的任何变量(也称为“全局”变量)在该实例中都是唯一的。当事件触发一个触发器函数时,它在自己的实例中运行,并且它设置的任何全局值仅对该实例可见。例如,由电子表格或文档UI调用的另一个函数将具有该非范围对象(全局)的自己的版本。
的定义和检索targetDocId
将是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 document
var link = target.getUrl();
var contents = target.getId();
cache.put("targetDocId", contents, 1500); // cache for 25 minutes
return contents;
}
现在,不要尝试使用全局变量,只需调用以下函数:
...
var targetDoc = DocumentApp.openById(get_targetDocId());
...
note缓存服务是可用于Google Apps脚本的永久存储的一个示例。该属性服务引入这个答案写后,是一个更轻量级的方式来坚持执行实例之间的“全局”变量。
观察:看来,您使用的是全局(静态)为tempate
和docName
,因为没有参数generatePersonDatasheet()
。您可以简单地动态生成targetDocId。
错误:在编写时,每次需要刷新缓存时get_targetDocId()
都会创建一个新副本docName
(15分钟)。您应该添加处理功能,以使文件可能已存在。(您的现有公司也是如此onOpen()
。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句