Switch statements are very rarely needed in Javascript. In general, you can simply use objects, such as dictionaries / maps, and search directly: foo.bar equivalent to foo['bar'] .
In addition, for the "global" variables, some_global_func() equivalent to window.some_global_func() , which can also be written as var f = 'some_global_func'; window[f]() var f = 'some_global_func'; window[f]() : you will never need eval to select a variable or call a function dynamically based on its name. In general, in doing so, you should prefer to store the function in the object, rather than in the global scope (i.e. in the window object).
So, if we assume that grid1_delete and grid2_delete fundamentally different and cannot be combined into a common function, you can do something like the following without changing your code:
var grid_actions = { 'grid1': { 'delete': function() { }, 'duplicate': function() { } }, 'grid2': { 'delete': function() { }, 'add': function() { }, 'duplicate': function() { } } } function contextMenuClick(context, menuItem) { var action = menuItem.innerHtml; if (context in grid_actions) { if (action in grid_actions[context]) { grid_actions[context][action](); } else { console.log('undefined action in contextMenuClick/' + context + ': ' + action); } } else { console.log('undefined context in contextMenuClick: ' + context); } }
The best solution, however, is to reorganize things to have these functions as object methods for each context, such as @ le dorfier .
Miles source share