jQuery Hotkeys - unbinding?

2019-05-10 10:45发布

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

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-05-10 11:21

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.

$(document).one("keydown.g", function(e) {
 // tab key
 if (e.which == "9") {
  e.preventDefault();
  // do something like focus on a field
  $("#target").focus();
  // once you've moved the focus, you can unbind and go back to tabbing normally
  $(document).unbind("keydown.g");
 } 
});

<3 Jquery

查看更多
beautiful°
3楼-- · 2019-05-10 11:24

Note that .unbind() doesn't support the eventData 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:

$(document).unbind('keydown'); // unbinds *all* keydown handers on the document

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:

function onkeydown(evt) {
   // do stuff
}

$(document).bind('keydown', '<%=(i+1)%>', onkeydown);

// later, in the dialog's "shutdown" code:
$(document).unbind('keydown', onkeydown);

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 using event.which inside your event handler to determine which key was pressed (which would then only require the handler be bound once).

查看更多
淡お忘
4楼-- · 2019-05-10 11:25

You can use

<script type="text/javascript">
$( document ).ready( function() {
    $(document).bind('keydown', '<%=(i+1)%>',function (evt) {
        // do stuff
    });
} );
</script>

This method binds events one time when document loaded.

查看更多
登录 后发表回答