如何在javascript中删除事件监听器?

时间:2013-02-26 22:23:57

标签: javascript jquery touch

我想知道如何添加一个事件监听器,你在jquery中使用on和off的方式?

document.removeEventListener('touchstart');
document.addEventListener('touchstart', function (e) {
     closePopupOnClick(e, popup);
});

但实际上并没有删除事件监听器。如果我将addEventListener代码放在一个函数中并将该函数传递给removeEventListener它将无法工作bc你不能将params传递给函数。有谁知道怎么做?

2 个答案:

答案 0 :(得分:16)

将侦听器作为变量并通过.addEventListener

附加
var myListener = function (e) {
    closePopupOnClick(e, popup);
};
document.addEventListener('touchstart', myListener, true);

然后在使用.removeEventListener

删除时再次传递它
document.removeEventListener('touchstart', myListener);

如果您在严格模式下,则可以使用arguments.callee

让听众自行删除
document.addEventListener('touchstart', function (e) {
    closePopupOnClick(e, popup);
    document.removeEventListener('touchstart', arguments.callee);
}, true);

如果您处于严格模式,则必须使用命名函数表达式,如果您想要一个函数自行删除

document.addEventListener('touchstart', function myListener(e) {
    closePopupOnClick(e, popup);
    document.removeEventListener('touchstart', myListener);
}, true);

如果你想在监听器中使用可能被某些东西改变的变量(例如循环),那么你可以编写一个生成器函数,例如

function listenerGenerator(popup) {
    return function (e) {
        closePopupOnClick(e, popup);
    };
}

现在,您可以使用listenerGenerator(popup)创建侦听器,它将调整popup变量的范围。请注意,如果popup对象,则它将是 ByRef ,因此可能仍会受到更改。

答案 1 :(得分:-1)

我认为这样做的一个好方法是自己添加一个事件,然后调用

event.stopImmediatePropagation()

例如:

htmlElement.addEventListener('touchstart', (event) => event.stopImmediatePropagation());

在 Chrome 中有类似的功能

htmlElement.removeAllListeners()

这可能会真正删除监听器。但我认为这不是一个明智的解决方案,因为其他浏览器似乎并没有很好地支持它。

相关问题