javascript - Replacing Switch-Case with something better? -



javascript - Replacing Switch-Case with something better? -

i working on web chat application. code see above used process info responses received in json format. how works ajax long-poll request sent server, pulls messages need sent user. outputs in json format, parsed js, , minte.processor.process(json) called handle rest.

i replace switch statement else. can see there quite few commands (and i'm estimating @ to the lowest degree 50 more) need more elegant solution. thinking of creating object holds array of key-value pairs key command name , value data, don't know if less efficient switch.

you create handler object knows how handle each command , has method each one. like:

var myhandler = { addchatnotice: function(content) { minte.ui.addchatnotice(content); }, changeusername: function(content) { minte.client.username = content; } //etc... }; minte.processor.process = function(json) { (var x in json) { var entry = json[x]; (var command in entry) { var content = entry[command]; //invoke handler function content myhandler[command](content); } } };

here's simple example: http://jsfiddle.net/xlrn5/

javascript

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

intellij idea - Update external libraries with intelij and java -

javascript - send data from a new window to previous window in php -