I am trying to add and remove an event listener to a button with javascript
callback:
let callback = (id) => alert(`This is a test Callback with id : ${id}`);
And it works when I use it with an event listener like this:
document.querySelector('#button').addEventListener('click', () => callback(id));
but with this approach I am not able to removeEventListener
because of the arrow function
.
Is there a proper workaround for this?
I am trying to add and remove an event listener to a button with javascript
callback:
let callback = (id) => alert(`This is a test Callback with id : ${id}`);
And it works when I use it with an event listener like this:
document.querySelector('#button').addEventListener('click', () => callback(id));
but with this approach I am not able to removeEventListener
because of the arrow function
.
Is there a proper workaround for this?
2 Answers
Reset to default 10You need a reference to the exact same function object, to be able to remove that specific event listener again.
So you have to store it into a variable, and then use that variable in both the addEventListener and removeEventListener calls.
let foo = () => callback(id);
document.querySelector('#button').addEventListener('click', foo);
// ...
document.querySelector('#button').removeEventListener('click', foo);
let func = () => callback(id);
document.querySelector('#button').removeEventListener('click', func);