最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add and Remove an Event Listener with an arrow function callback - Stack Overflow

programmeradmin4浏览0评论

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?

Share Improve this question asked Aug 6, 2020 at 10:12 Ivan TaccadoliIvan Taccadoli 1831 silver badge18 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10

You 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);
发布评论

评论列表(0)

  1. 暂无评论