I have a jQuery Dialog which initializes hotkeys as follows:
<script type="text/javascript">
$(document).bind('keydown', '<%=(i+1)%>',function (evt) {
// do stuff
});
</script>
This loops through 1-9...
Problem is, if you close the dialog and then reopen the dialog. It keeps re-binding, so when you do a keydown on '1', it then runs twices, three times, four times, etc... it just keeps growing.
I tried killing the keybindings on dialog close with
$(document).unbind('keydown', '1');
$(document).unbind('keydown', '2');
$(document).unbind('keydown', '3');
$(document).unbind('keydown', '4');
$(document).unbind('keydown', '5');
$(document).unbind('keydown', '6');
$(document).unbind('keydown', '7');
$(document).unbind('keydown', '8');
$(document).unbind('keydown', '9');
But that had no effect. Any ideas on how to handle this?
Thanks
I resolved a similar issue using a namespace for the keydown event in conjunction with one()
note the .g in "keydown.g". That puts it in a separate scope which I can later unbind without unbinding every keydown in the document.
<3 Jquery
Note that
.unbind()
doesn't support theeventData
argument, which is why your unbinds aren't working.Off the top of my head, you have two different approaches here. If these are the only document-level keydown bindings, you can to a "full" unbind as follows:
Alternatively, you can store your keydown handler as a non-anonymous function and keep a reference around to pass back to unbind when closing the dialog:
I'm not 100% positive how this works when the same function is bound multiple times, however. You're probably better off eliminating the
eventData
and usingevent.which
inside your event handler to determine which key was pressed (which would then only require the handler be bound once).You can use
This method binds events one time when document loaded.