如何删除使用闭包添加的EventListener? [英] How to removeEventListener that was added using closure?

查看:127
本文介绍了如何删除使用闭包添加的EventListener?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这基本上是对此的后续问题:无法将事件传递给addEventListener:关闭问题

This is basically a followup question to this: Can't pass event to addEventListener: closure issue.

我几乎阅读了所有相关问题,但找不到答案。

I have read almost every related question and can't find the answer to this.

以下函数在循环中执行,其中参数从数据数组中提取。
使用此函数,我可以将不同/新参数传递给事件侦听器的每个实例。 outer函数允许将参数的值封装在闭包中,以便实际值可用,而不仅仅是对持有者的引用。此外,passevent功能将事件传递给响应函数。最后,响应函数具有所有适当的信息以响应click事件。这非常有效。
问题是,我无法弄清楚如何在以后删除事件监听器。我已经尝试了所有我能想到的东西。请帮忙。我该怎么做:removeEventListener?

The function below is executed within a loop where the parameters are pulled from an array of data. With this function I am able to pass different/new parameters to each instance of an event listener. The outerfunction allows for the values of the parameters to be encapsulated within closure so that the actual values are available, not just references to the holders. Additionally, the passeventfunction passes the event to the responsefunction. Finally, the responsefunction has all the appropriate info in order to respond to the click event. This works great. The problem is, I can't figure out how to remove the event listener at a later time. I have tried everything that I can think of. Please help. How can I: removeEventListener ?

(function outerfunction(i, f) {
     elementname.addEventListener("click", function passeventfunction(e) { 
         responsefunction(e, f, i); });})(parameter1, parameter2);

此外,如果有人可以帮助清理这里发生的事情。这是封闭内的闭包吗?是否有留下内存泄漏的危险?谢谢!

also, if someone could help clear up what is happening here. Is this a closure within a closure? Is there a danger of leaving a memory leak or something? Thanks!

推荐答案

您必须保留对您的听众的引用:

You have to keep references to your listeners:

var listeners = {};
for(/* ... */) {
   (function outerfunction(i, f) {
        var listener = function(e) { 
            responsefunction(e, f, i); 
        }
        elementname.addEventListener("click", listener);
        listeners[elementname.id] = listener; // use something meaningful 
                                              // as your keys
   })(parameter1, parameter2);
}

// Removing the listener later:
elementname.removeEventListener("click", listeners[elementname.id]);

这篇关于如何删除使用闭包添加的EventListener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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