title: Library Defined Google Sheets Menu
body: <p>I'm currently working on a way to distribute updates to Google Sheets without the user having to update anything at their end. This is in line with a specification I am having to meet.
  This is so far accomplished using apps script libraries and boilerplate code for each sheets bound script.</p>
  
  <p>A desire has now arisen to have custom menus within the sheets, whose menu text and functions are also centrally updatable. My thoughts on how to accomplish this were to have the menu items and their associated functions defined as followed in the library.</p>
  
  <pre><code>function getMenu() {
    var menus = []
    var obrMenu = {name: 'obrMenu', menuItems: []};
    obrMenu['menuItems'].push({name: "Alert", func: "alert('Success')"});
    menus.push(obrMenu);
    return menus;
  }
  </code></pre>
  
  <p>Then within the container scripts use the following to translate this into something usable to create the menus with.</p>
  
  <pre><code>function onOpen() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var menus = lib.getMenu();
    for (var i = 0; i &lt; menus.length; i++) {
      var cur = menus[i];
      var items = cur['menuItems'];
      var menuItems = []; 
      for (var j = 0; j &lt; items.length; j++) {
        var curFunc = new Function(
         "return function " + items[j]['name'] + "(){" + items[j]['func'] + "}"
        )();
        menuItems.push({name: items[j]['name'], funcName: curFunc.name});
      }
      ss.addMenu(cur['name'], menuItems);
    }
  }
  </code></pre>
  
  <p>This method when ran, produces the error</p>
  
  <pre><code>Invalid argument: subMenus (line 15, file "Code")
  </code></pre>
  
  <p>with subMenus being the Apps Script argument name for what I have called <code>menuItems</code>. Whilst I gather this issue is probably down to the scoping of the produced functions, I can not seem to see how to get round it.</p>
  
  <p>Any suggestions would be greatly appreciated. Many thanks.</p>