jqueryevent-handlingbindjquery-eventsunbind

jQuery unbinding a large number of events


I'm writing a program with two keyboard modes using jquery.hotkeys.js, I'm seeing some slowdown and flashing when unbinding all keydown events. Is there a better way to do this?

function bindAll() {
    //bind all keystroke events
    $(document).bind('keydown','a', function(evt) {
    //...
    }
    $(document).bind('keydown','b', function(evt) {
    //...
    }
    //etc...
}

function unbindAll() {
     $(document).unbind('keydown');
     return true;
} //end unbinding all keystrokes

Solution

  • jQuery offers you the possibility to create namespaces for events. That looks like:

    $(document).bind('keydown.mySpace', function(evt) {
    });
    $(document).bind('keyup.mySpace', function(evt) {
    });
    
    // etc.
    

    You can .unbind() all the events which were added to a namespace then like so:

    $(document).unbind('.mySpace');
    

    I'm not aware of the plugin you mentioned, but you should have a look into the docs or even better the source. If it's well designed you should be able to use the jQuery event namespaces for that purpose.