简体   繁体   English

当处理程序需要接收回调函数时,删除jQuery事件侦听器

[英]Remove jQuery event listener when the handler needs to receive a callback function

I have a listener: 我有一个听众:

$(document).on("keypress", function(e){ebClose(e,mpClose)});

I am trying to figure out how to delete it dynamically. 我试图弄清楚如何动态删除它。 The challenge is that I really want ebClose to receive mpClose as a callback function, because in other instances ebClose would receive different callback functions. 挑战在于,我确实希望ebClos​​e接收mpClose作为回调函数,因为在其他情况下,ebClos​​e会接收不同的回调函数。

What ebClose does is this: ebClos​​e的作用是:

function ebClose(e, callback){
    if (e.which == 13){
        callback();
    }
}

Which is to say, it checks if it is the enter key, and then calls the callback function. 也就是说,它检查它是否是enter键,然后调用回调函数。 In theory, I could make 10 different versions of ebClose and paste in the different functions to avoid needing a callback, but it seems like it is a lot of code. 从理论上讲,我可以制作10个不同版本的ebClos​​e并粘贴不同的函数,以避免需要回调,但是看来这是很多代码。 Any suggestions out there for a strategy to be able to delete this listener when needed? 有什么建议可以在需要时删除此侦听器的策略吗?

This obviously doesn't work: 这显然行不通:

$(document).off("keypress", function(e){ebClose(e,mpClose)});

And if I change it to this: 如果我将其更改为:

$(document).on("keypress", ebClose);

Then I can delete it, but don't know how to pass the callback. 然后,我可以删除它,但不知道如何传递回调。 Thanks for suggestions. 感谢您的建议。

One option is to namespace the events . 一种选择是为事件命名空间

Example Here 这里的例子

// Attach a keypress event namespaced to 'ebclose'
$(document).on("keypress.ebclose", function(e) {
  ebClose(e, mpClose)
});

// Remove the namespaced event:
$(document).off("keypress.ebclose");

Alternatively, you could also use $.proxy() to bind the function: 另外,您也可以使用$.proxy()绑定函数:

Example Here 这里的例子

$(document).on("keypress", $.proxy(ebClose, this, mpClose));

function ebClose(callback, e){
    if (e.which == 13){
        callback();
    }
}
function mpClose () {
    alert('Remove the event listener');
    $(document).off("keypress", $.proxy(ebClose, this, mpClose));
}

Or, similarly, you could use the .bind() method : 或者,类似地,您可以使用.bind()方法

Example Here 这里的例子

$(document).on("keypress", ebClose.bind(this, mpClose));

function ebClose(callback, e){
    if (e.which == 13){
        callback();
    }
}
function mpClose () {
    alert('Remove the event listener');
    $(document).off("keypress", ebClose.bind(this, mpClose));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM