'How to remove a curried Event Listener
I have an addEventListener that is using a curried function so then I can use the parameters of the function.
const curryFunction = (product) => {
return function curry(e) {
//do stuff here
}
}
const addEvent = (product) => {
document.getElementById('button').addEventListener('click', curryFunction(product))
}
but I want to be able to remove it, I've looked up similar questions to this on stack overflow, but as they didn't have this specific case they didn't seem to work. I tried
document.getElementById('button').removeEventListener('click', curryFunction(product)) // just didn't do anything
document.getElementById('button').removeEventListener('click', curryFunction()) // gave me error
document.getElementById('button').removeEventListener('click', curry()) // gave me error
along with the similarities such as
document.getElementById('button').removeEventListener('click', curryFunction)
document.getElementById('button').removeEventListener('click', curryFunction(product))//this one was nested inside a function so I wouldn't get an error || product had the same value as the product in the addEvent(product)
document.getElementById('button').removeEventListener('click', curry)
document.getElementById('button').removeEventListener('click', curry(e))//this one was nested inside a function so I wouldn't get an error with the e
and none of them worked, so what are the ways to do either
- Remove a curried eventListener function or
- Have a eventListener without
.bind()because that didn't work either
Solution 1:[1]
The issue is that removeEventListener requires a reference to the same exact "object", because it will use object identity to see which listener to remove.
The curryFunction function creates a new instance every time it is called, so you have to keep track of that function in order to remove it later on:
var myListener = undefined;
const addEvent = (product) => {
// Store the reference to the listener somewhere
myListener = curryFunction(product);
document.getElementById('button').addEventListener('click', myListener)
}
// later on use myListener to remove the listener
document.getElementById('button').removeEventListener('click', myListener)
Note that in this case if addEvent is called twice without calling removeEventListener in between you will lose the reference. So either you should check, before adding a new listener, that you don't have already one in place/you remove the existing one or you can use an array/object to keep track of multiple listeners at the same time.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GACy20 |
