Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to removeEventListener that was added using closure?

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?

like image 893
William Smith Avatar asked Nov 04 '13 18:11

William Smith


People also ask

Are event listeners removed when element is removed?

In modern browsers, if a DOM Element is removed, its listeners are also removed from memory in javascript. Note that this will happen ONLY if the element is reference-free. Or in other words, it doesn't have any reference and can be garbage collected. Only then its event listeners will be removed from memory.

What is the syntax to remove a listener from an event?

The removeEventListener() is an inbuilt function in JavaScript which removes an event handler from an element for a attached event. for example, if a button is disabled after one click you can use removeEventListener() to remove a click event listener.


1 Answers

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]);
like image 179
bfavaretto Avatar answered Nov 16 '22 01:11

bfavaretto