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?
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:
Then, in your
keyupevent handler, you can simply refer to the appropriate property of this object:One notable disadvantage of this method over a
switchstatement would be that it’ll look much messier if you want multiple keys to perform the same function. With aswitch, you could just let those cases fall through. Here, you’ll have to perform some other assignments after the initalkeyHandlersdeclaration.A couple of other points… you should use
addEventListenerrather than theon...properties, and is there a reason you’ve named the function you are assigning toonkeyupcurrently? The only reason to name it would be if you needed to refer to it from within itself.