简体   繁体   English

如何删除使用闭包添加的EventListener?

[英]How to removeEventListener that was added using closure?

This is basically a followup question to this: Can't pass event to addEventListener: closure issue .这基本上是一个后续问题: Can't pass event to addEventListener:closure issue

I have read almost every related question and can't find the answer to this.我已经阅读了几乎所有相关问题,但找不到答案。

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.此外,passeventfunction 将事件传递给 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 ?我怎样才能: 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?是否有留下内存泄漏之类的危险?

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

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

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