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 fuction for each context/choice:
grid1_delete()
grid1_duplicate()
grid2_delete()
grid2_add()
grid2_duplicate()
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:
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);
}
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 the related posts, but I'm not quite getting how to apply them to this exact situation.