-1

I have an application with 3 keyboard shortcuts. They only get fired if the focus is within a row on a grid, so I have added a listener to handle this:

if (grid) {
    var host = grid.hostElement;
    //handle the keydown event
    host.addEventListener('keydown', function (e) {
        if (e.altKey && e.key == "q") {  
           doSomething(grid);
        }

        if (e.altKey && e.key == "n") {
           doSomethingElse(grid);
        }
        if (e.altKey && e.key == "u") {
            doAThirdThing(grid);
        }
    });

}

This is working fine, but is this the most efficient way to handle this, from a performance standpoint? Should I be using a switch or multiple listeners instead?

alemus
  • 314
  • 1
  • 2
  • 17

2 Answers2

4

A few issues, for cross-browser compatibility get your keycode with:

    var key = e.which || e.keyCode;

to support all browsers. Secondly, e.key doesn't have very good browser support (https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key). Even though it says e.key is supported in Chrome 45.0 I see it as undefined in 45.0.2454.85 m. Here is an alternative:

    host.addEventListener('keydown', function (e) {
        var key = e.which || e.keyCode;
        if(e.altKey){
            switch(key){
                case 81:
                    // "q"
                    doSomething(grid);
                    break;
                case 78:
                    // "n"
                    doSomething(grid);
                    break;
                case 85:
                    // "u"
                    doSomething(grid);
                    break;
            }
        }
    });
Jordan
  • 3,813
  • 4
  • 24
  • 33
1

You can use a switch case statement as you're always checking that e.altKey is the same value. Like this:

 if (grid) {
    var host = grid.hostElement;
    //handle the keydown event
    host.addEventListener('keydown', function (e) {
        if (e.altKey){
            switch(e.key){
                case "q":
                    doSomething(grid);
                break;

                case "n": 
                   doSomethingElse(grid);
                break

                case "u":
                    doAThirdThing(grid);
                break;
            }
        }
    });
}

Think of value e as a biscuit in a jar, and with every if statement you place your hand in the jar and check what the biscuit is, then place it back in the jar. This then happens on every conditional IF statement, which isn't very efficient.

If you use a switch statement it's the same as getting the biscuit out of the jar and holding it in your hand - you can check the biscuit and any of its attributes much faster.

Read more about switch statements here : http://www.w3schools.com/js/js_switch.asp

dj10dj100
  • 305
  • 2
  • 12