How to remove an EventListener that has been added using closure?

This is basically the next question: Unable to pass the addEventListener event: close problem .

I read almost every related question and cannot find the answer to this question.

The function below is executed in a loop where the parameters are pulled from the data array. With this function, I can pass different / new parameters to each instance of the event listener. An external function allows you to encapsulate parameter values ​​within closures so that actual values ​​are available, not just references to holders. In addition, the passevent function passes the event to the response function. Finally, the response function has all the necessary information to respond to the click event. This works great. The problem is that I cannot figure out how to remove the event listener later. I tried everything I could 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 can help clarify what is happening here. Is this closing in closing? Is there a danger of leaving a memory leak or something else? Thanks!

+7
javascript closures javascript-events addeventlistener
source share
1 answer

You should keep links 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]); 
+8
source share

All Articles