首页 > 解决方案 > 你可以在谷歌脚本中自我引用回调代码吗?

问题描述

我仍在试图弄清楚谷歌的脚本库的东西。我遇到的一个限制是回调。似乎您不能让回调引用库(即使它起源于那里),因此您必须创建一个本地回调,然后调用库回调。

让我解释:

库 LIB_A:

/*
 Populates the drop-down menu on the sheet
 */
function onOpen() {
  var tenantMenu = ui.createMenu("Tenant")
  tenantMenu.addItem("Add Tenant", "showAddTenantDialog")
  topMenu.addSubMenu(tenantMenu)
  topMenu.addToUi()

function showAddTenantDialog() {
...
}

在导入 LIB_A 的代码中,要使其正常工作,我似乎必须具备:

/* This function is called by the sheet when it is opened.  I understand why this is required */
function onOpen() { 
  /* create the menu */
  LIB_A.onOpen()
}

/* Callback from the menu (that is actually in LIB_A) */
function showAddTenantDialog() {
  /* Call the intended function that resides in LIB_A */
  LIB_A.showAddTenantDialog()
}

我真的很想让我的 LIB_A 代码看起来像这样:

tenantMenu.addItem("Add Tenant", "LIB_A.showAddTenantDialog")

所以我只需要在导入 LIB_A 的代码中使用它。

function onOpen() {
  LIB_A.onOpen()
}

标签: google-apps-script

解决方案


推荐阅读