1

I want to pass in a eventListener with a parameter in addEventListener. For example, like this:

  elems.forEach((elem, index) => {
    elem.addEventListener('click', () => handleClick(index));
  });

And then I want to removeEventListener, however because I passed in an anonymous callback, I can't reference it and can't pass it in removeEventListener as an argument.

  • 1
    "I can't reference it" — So keep a reference to it. – Quentin Dec 19 '21 at 22:01
  • Use [event delegation](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of assigning multiple event listeners — it’s more maintainable, and applies to dynamically added elements. E.g., use an [event argument](//developer.mozilla.org/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback)’s [`target`](//developer.mozilla.org/docs/Web/API/Event/target). See [the tag info](/tags/event-delegation/info) and [What is DOM Event delegation?](/q/1687296/4642212). Then no event listeners need to be removed; keep the logic in a single listener. – Sebastian Simon Dec 19 '21 at 22:04
  • This isn't *quite* the same as those, but close. The challenge is, you want to create a dynamic function to apply a function, but it needs to be a reference available elsewhere. Consider using `const elemHandlers = elems.map(/* create the listener function, add the event listener, and return the listener function for later removal */);` – Snowmonkey Dec 19 '21 at 22:06
  • You can now pass an [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) to addEventListener, allowing you to detach the listener from outside with no pain. – Kaiido Dec 20 '21 at 02:35

0 Answers0