gpt4 book ai didi

google-apps-script - Google Apps 脚本 - 错误 : script function not found when library used

转载 作者:行者123 更新时间:2023-12-03 21:29:50 57 4
gpt4 key购买 nike

当我使用 UiApp 在电子表格中创建脚本时,我有一个带有服务器处理程序的按钮,该服务器处理程序以下划线结尾。如果我从电子表格中运行脚本,那么它工作正常,但如果我将这个项目添加到另一个工作表中并运行它,那么我会收到一条错误消息,指出找不到脚本函数。在代码中使用以下划线结尾的函数时,查找函数没有问题,似乎只是在从服务器处理程序调用它们时。

复制:

创建一个新的电子表格

插入代码:

function buildForm() {
var app = UiApp.createApplication();

// show that calling a function ending in underscore works
var labelText = getLabelText_();

app.add(app.createLabel(labelText).setId("label"));

var handler = app.createServerHandler("clickHere_");
app.add(app.createButton("Click Here",handler));

var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.show(app);
}

// This is just to show that underscore on the end works as long as it is not a server handler
function getLabelText_() {
return "label text";
}


// called from server handler
function clickHere_(e) {
var app = UiApp.getActiveApplication();
app.getElementById("label").setText("You clicked there");
return app;
}

运行代码,看看它是否按预期工作

创建另一个电子表格,将第一个电子表格添加为库并将其命名为 MyCode。确保您已保存版本等。

在新的电子表格中,插入代码:

function runIt() {
MyCode.buildForm()
}

运行这段代码,注意 getLabelText_() 工作正常并创建了 UI,但是当您按下按钮时,会出现找不到函数的错误。

如果我从 clickHere_(e) 中删除下划线并相应地更改服务器处理程序,那么它就可以工作。

是否是从服务器处理程序调用的所有函数末尾删除下划线的唯一解决方案?

最佳答案

这是谷歌应用程序脚本库所需的组件:
https://developers.google.com/apps-script/guide_libraries#writingLibrary
这是为了实现私有(private)函数而设计的。

编辑:

正如文档中所说:

If you want one or more methods of your script to not be visible (nor usable) to your library users, you can end the name of the method with an underscore. For example, myPrivateMethod_()

作为“库函数”,function buildForm() 可以调用也在该库中的function getLabelText_()。但是您不能使用该库从脚本中直接调用 function getLabelText_()。您的脚本均无权直接调用 function clickHere_(e)
因此,当用作服务器处理程序时,函数 clickHere_(e) 是从脚本而不是库中调用的,它不会工作。要调用此函数,您应该删除其末尾的“_”并以这种方式调用它:libraryName.libraryFunction();

关于google-apps-script - Google Apps 脚本 - 错误 : script function not found when library used,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21566059/

57 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com