G
G
Grigory Boev2020-03-01 15:47:02
Google Apps Script
Grigory Boev, 2020-03-01 15:47:02

How to pass arguments to a function called from a menu?

Good afternoon. There is a task - to make the menu which items are loaded from the table.
With a static menu, I do this:

function onOpen() { 
  //Выполняется при открытии
  SpreadsheetApp
  .getUi()
  .createMenu('Меню')
  .addItem('Функция1','function1')
  .addItem('Функция2','function2')
  .addToUi();
};

How can you pass any parameters to the function, or find out which menu item was called if you make the same names for the functions? There is an option - to call the functions menuItem1 , menuItem2 , menuItem3 , etc. and for each, make a click handler that will call the target function with the necessary data, but this is a crutch. In the Google help, the functions are also specified as a string and nothing is said about the parameters.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ivanov, 2020-03-01
@ProgrammerForever

Let's say you have a menu description for some function

var MENU = [
  {
    caption: 'Пункт меню 1',
    functionName: 'itemMenu',
  },
  {
    caption: 'Пункт меню 2',
    functionName: 'itemMenu',
  },
  {
    caption: 'Пункт меню 3',
    functionName: 'itemMenu',
  },
];

Obviously, in addition to the main menu, you can also build a menu from this array
function onOpen() {
  var ui = SpreadsheetApp.getUi();

  var menu = ui.createMenu('Test');

  MENU.forEach(function(item, i) {
    menu.addItem(item.caption, item.functionName + i);
  });

  menu.addToUi();
}

Let's say it itemMenuworks like this
function itemMenu(e) {
  var caption = e.item.caption;
  var order = e.order;
  Browser.msgBox(
    Utilities.formatString('Был нажат %sй пункт меню: %s', order + 1, caption)
  );
}

Then you can pass the wrapped callbacks with the given argument to the global context
(function(self) {
  MENU.forEach(function(item, i) {
    self[item.functionName + i] = function() {
      return self[item.functionName]({ item: item, order: i });
    };
  });
})(this);

Full listing here
5e5bcdbc5dd9e315037179.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question