我有一个听众:

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


我试图弄清楚如何动态删除它。挑战在于,我确实希望ebClos​​e接收mpClose作为回调函数,因为在其他情况下,ebClos​​e会接收不同的回调函数。

ebClos​​e的作用是:

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


也就是说,它将检查它是否为enter键,然后调用回调函数。从理论上讲,我可以制作10个不同版本的ebClos​​e并粘贴不同的函数,以避免需要回调,但是看来这是很多代码。有什么建议可以在需要时删除此侦听器的策略吗?

这显然行不通:

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


如果我将其更改为:

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


然后,我可以删除它,但不知道如何传递回调。感谢您的建议。

最佳答案

一种选择是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");




另外,您也可以使用$.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));
}


或者,类似地,您可以使用.bind() method

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));
}

关于javascript - 当处理程序需要接收回调函数时,删除jQuery事件监听器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33828496/

10-12 15:13
查看更多