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?
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.
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.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With