PDA

View Full Version : switch() alternative ?!


Vladdy
03-30-2003, 02:58 PM
I had a flashback from my C++ programming days and thought why not apply it in JavaScript...

Consider a very common task: branching execution based on the value of a string variable.
"Novice" approach:

function processEvent(event)
{ if(event=='dothis') { /* do this */ }
if(event=='dothat') { /* do that */ }
if(event=='domore') { /* do more */ }
}


"Intermediate" approach:

function processEvent(event)
{ switch(event)
{ case 'dothis': /* do this */ break;
case 'dothat': /* do that */ break;
case 'domore': /* do more */ break;
}
}


"Expert" approach (avoiding mile long functions):

function processEvent(event)
{ switch(event)
{ case 'dothis': doThis(); break;
case 'dothat': doThat(); break;
case 'domore': doMore(); break;
}
}

function doThis() { /*do this*/ }
function doThat() { /*do that*/ }
function doMore() { /*do more*/ }


Now, what do you think of:

function processEvent(event)
{ return eventHandlers[event]();
}
var eventHandlers = new Array();
eventHandlers['dothis'] = function { /*do this*/ }
eventHandlers['dothat'] = function { /*do that*/ }
eventHandlers['domore'] = function { /*do more*/ }

:thumbsup:

liorean
03-30-2003, 03:22 PM
Nice construct. I don't understand why you need the processEvent(event) function when you have the collection, though. You should be able to tap directly into the collection.

Oh, and another way to do it:
eventHandler={
dothis: function(){},
dothat: function(){},
domore: function(){}
};

// Called like this:
eventHandler['dothis'|'dothat'|'domore']();

Vladdy
03-30-2003, 04:01 PM
absolutely,

I was just showing the progression...