Note that there are some explanatory texts on larger screens.

plurals
  1. POhow to avoid nested switch?
    text
    copied!<p>I'm creating a contextual menu in JavaScript for a web app. The menu can appear in numerous contexts, and have different choices. I could have a different function for each context/choice:</p> <pre><code>grid1_delete() grid1_duplicate() grid2_delete() grid2_add() grid2_duplicate() </code></pre> <p>and hard code those in as the menu is being built. The thing I don't like about that is there will probably be a lot of repeated code. So I was thinking about using a dispatcher function, but it's resulting in potentially long, nested switch statement thus:</p> <pre><code>function contextMenuClick(context, menuItem) { var action = menuItem.innerHTML; switch (context) { case 'grid1': switch(action) { case('delete'): // do delete for grid1 break; case('duplicate'): // do duplicate for grid1 break; default: console.log('undefined action in contextMenuClick/grid1: ' + context); } break; case 'grid2': switch(action) { case('add'): // do add for grid2 break; case('delete'): // do delete for grid2 break; case('duplicate'): // do duplicate for grid2 break; default: console.log('undefined action in contextMenuClick/grid2: ' + context); } break; default: console.log('undefined context in contextMenuClick: ' + context); } </code></pre> <p>Yuck. There's got to be a better way. Maybe the dispatcher is more trouble than it's worth. I've looked at some of <a href="https://stackoverflow.com/questions/496189/what-is-the-best-easiest-way-to-use-nested-switch-case-statements">the</a> <a href="https://stackoverflow.com/questions/494506/dealing-with-nested-if-then-else-nested-switch-statements">related</a> <a href="http://www.codinghorror.com/blog/archives/000486.html" rel="nofollow noreferrer">posts</a>, but I'm not quite getting how to apply them to this exact situation.</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