开发者

Unbinding a JQuery hotkey inside the handler function

开发者 https://www.devze.com 2023-03-31 17:48 出处:网络
I am using JQuery with the hotkeys plugin and having trouble unbinding an event. Specifically, I am trying to unbind a keypress event within the method that has been 开发者_Python百科bound to that key

I am using JQuery with the hotkeys plugin and having trouble unbinding an event. Specifically, I am trying to unbind a keypress event within the method that has been 开发者_Python百科bound to that keypress.

For example:

$(document).bind('keydown', 'space', doStuff)

function doStuff() {
    alert("Doing stuff");
    $(document).unbind('keydown', 'space');
}

I think I might have misunderstood the unbind call API - do I need to provide the third parameter ? In some documentation, it seems I must provide the function handler which I originally provided to bind as this parameter - but that function handler is the very function I am calling unbind from, so I have no handle to it ? or do I ?

Note that before today, I was using:

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

This worked fine - I need to bind and unbind "space" at several points in the code, and this did the trick. But now I also have been binding OTHER key presses, and found this call was (not surprisingly) unbinding all key presses for all keys.

So how can I unbind some or all events for a specific key press, either using the hotkeys plugin, or without it ?


You need to use namespaces.

$(document).bind('keydown.space', 'space', doStuff)

function doStuff() {
    alert("Doing stuff");
    $(document).unbind('keydown.space', 'space');
}
0

精彩评论

暂无评论...
验证码 换一张
取 消