Search code examples
javascriptjquerybackbone.js

Enabling keyboard listener (ctrl+Z) on specific DOM element


I am trying to bind the keyboard event ctrl+z through jquery only when a backbone view is rendered and when view is removed, I am unbinding it. But the problem is I want to unbind only the ctrl+z event only for current view.

on Initializing view:

$(document).keydown(function(e){
                if((e.which === 90 && e.ctrlKey && e.shiftKey) || (e.which === 89 && e.ctrlKey)){
                    console.log('control + shift + z || control + y');
                    //redoAction;
                }
                else if(e.which === 90 && e.ctrlKey){
                    console.log('control + z');
                    //undoAction;
                }          
            }); 

On removing view:

$(document).off('keydown'); 

But the last statement will unbind all the keyboard listeners. I don't want that.


Solution

  • Give a name to your handler function in a declaration (or by assigning it to a variable). Then you can use that name to refer the handler within .off():

    // Create a named function
    function handler (e) {
        if((e.which === 90 ...)
    }
    
    // Attach event
    $(document).on('keydown', handler);
    //Detach event
    $(document).off('keydown', handler);