1

I'm refactoring some javascript to use jQuery and one of the events looks something like this

document.onkeyup = function keyUp(e) {

if (e.keyCode == 70) { // 'f'
    //Do something
}
else if (e.keyCode == 78) { // 'n'
    //Do something else
} ...

Unfortunately the things done in the cases aren't as similar or as simple as those in this question. Is there a better way to write this instead of a massive hard-coded if/else or switch/case statement?

Community
  • 1
  • 1
cat dad
  • 218
  • 4
  • 12
  • 3
    It largely depends on what the "do something" is. – Ja͢ck Feb 05 '13 at 07:44
  • possible duplicate of [Alternative to a million IF statements](http://stackoverflow.com/questions/10029089/alternative-to-a-million-if-statements) – Bergi Feb 05 '13 at 07:53
  • Unfortunately the "do something" varies a bit (though there are a lot of simply loading urls at the moment) and I'd love to use something that is easily extensible. – cat dad Feb 05 '13 at 08:01

2 Answers2

4

I don't know if it's really better but you could list all of the possible values as keys of an object in some other dedicated file that you include. For example:

var keyHandlers = {
    "70": function () { /* Do something */ },
    "78": function () { /* Do something else */ }
};

Then, in your keyup event handler, you can simply refer to the appropriate property of this object:

document.onkeyup = function keyUp(e) {
    keyHandlers[e.keyCode]();
};

One notable disadvantage of this method over a switch statement would be that it'll look much messier if you want multiple keys to perform the same function. With a switch, you could just let those cases fall through. Here, you'll have to perform some other assignments after the inital keyHandlers declaration.


A couple of other points... you should use addEventListener rather than the on... properties, and is there a reason you've named the function you are assigning to onkeyup currently? The only reason to name it would be if you needed to refer to it from within itself.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • Don't forget the `e.keyCode in keyHandlers` test. – Bergi Feb 05 '13 at 07:54
  • Thanks! To answer your question, this was code written by someone else so I don't know why named it. I'm thinking of using something like $(document).on("keyup",this.keyUpHandler); – cat dad Feb 05 '13 at 07:59
2

Use an object to map key codes to functions:

var keyTable = {
  70: function () { ... },
  78: function () { ... },
  ... etc ...
}

Then your event handler becomes:

document.onkeyup = function keyUp(e) {
  keyTable[e.keyCode]();
};
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
Chris Tavares
  • 29,165
  • 4
  • 46
  • 63