Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Switch statements are very rarely necessary in Javascript. In general, you can just use objects like dictionaries/maps and do the lookup directly: <code>foo.bar</code> is equivalent to <code>foo['bar']</code>.</p> <p>Also, for "global" variables, <code>some_global_func()</code> is equivalent to <code>window.some_global_func()</code>, which can also be written as <code>var f = 'some_global_func'; window[f]()</code>: you don't <em>ever</em> need <code>eval</code> in order to select a variable or call a function dynamically based on its name. In general, when doing that, though, you should prefer to store the function in an object rather than at global scope (i.e. in the <code>window</code> object).</p> <p>So, assuming that <code>grid1_delete</code> and <code>grid2_delete</code> are fundamentally different and can't be combined into a generic function, you could do something like the following without changing your code much:</p> <pre><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); } } </code></pre> <p>A better solution, though, is to refactor things to have have these functions be methods of objects for each context, like @<a href="https://stackoverflow.com/users/31641/le-dorfier">le dorfier</a> suggests.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload