如何在javascript中删除事件监听器? [英] How to remove an event listener in javascript?

查看:207
本文介绍了如何在javascript中删除事件监听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am wondering how can I remove an event listener after adding one, the way you use on and off in jquery?

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

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

but this does not actually remove the event listener. If I put the addEventListener code in a function and pass that function into the the removeEventListener it will not work bc you cannot pass params into the function. Anyone know how to do this?

推荐答案

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

Put the listener as a variable and attach via .addEventListener

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

然后在使用 .removeEventListener

then pass it again when removing with .removeEventListener

document.removeEventListener('touchstart', myListener);






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


If you're not in strict mode you can make a listener remove itself with arguments.callee

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

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

If you are in strict mode, you have to use a named function expression if you want a function to remove itself

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






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


If you want to use variables in the listener that may be changed by something (e.g. a loop), then you can write a generator function, for instance

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

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

Now you can create the listener with listenerGenerator(popup) and it will scope the popup variable. Note that if popup is an Object, it will be ByRef and therefore may still be subject to changes.

这篇关于如何在javascript中删除事件监听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆