简体   繁体   中英

Google Apps Script Library nested function not found

I have a library with the following code

function onOpen() {
  SpreadsheetApp.getUi()
      .createMenu('Generate Code')
      .addItem('iOS', 'generateIOS')
      .addItem('Android', 'generateAndroid')
      .addToUi();
}

and in a different file in the same library I have

function generateAndroid(){
  generateFile('Android');
}

function generateIOS(){
  generateFile('iOS');  
}

Now, I'm using the library in a script

function onOpen(){
 Library.onOpen(); 
}

But I get

Script function not found: generateIOS For more information, see https://developers.google.com/apps-script/reference/base/menu#addItem(String,String)

If I create a generateIOS function in the script that's using the library, it works. How do I solve this problem?

generateAndroid() and generateIOS() don't exist in the global namespace, they exist in the library's namespace. So when you add items to the UI which call "generateIOS" and "generateAndroid", the script tries to run them from the same context as onOpen() and fails to find them. Remember that addItem() takes a pair of Strings as parameters, so it's a pretty dumb function and doesn't know that you're referring to the "Library" functions instead of the global ones.

There are two possible solutions I see:

1) Add global functions that simply pass the function call along to Library.

// inside the global context
function generateAndroid(){
    Library.generateAndroid();
}
function generateIOS(){
    Library.generateIOS();
}

2) Try adding the Library namespace to the addItem() string (note: I have NO idea if this will even work but it's worth a shot.

.addItem('iOS', 'Library.generateIOS')
.addItem('Android', 'Library.generateAndroid')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM