How to removeEventListener that was added using closure?

穿精又带淫゛_ 提交于 2019-12-04 03:03:33

问题


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.

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!


回答1:


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


来源:https://stackoverflow.com/questions/19774202/how-to-removeeventlistener-that-was-added-using-closure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!