- From: Keith Cirkel <notifications@github.com>
- Date: Thu, 31 Jul 2025 00:58:41 -0700
- To: whatwg/dom <dom@noreply.github.com>
- Cc: Subscribed <subscribed@noreply.github.com>
- Message-ID: <whatwg/dom/issues/1396/3138932602@github.com>
keithamus left a comment (whatwg/dom#1396) I'm not sure listeners attached directly to an element cause memory leaks in the way described in the post. It's likely they're experiencing leaks for other reasons. Do you have emperical proof of memory leaks for such a scenario? Calling `addEventListener()` adds the event to the listener map which is attached to the element, so removing the element and allowing it to be freed will free all listeners. In this way listeners are always "weak". Memory leaks tend to happen when JS holds a strong reference to an element that has been removed. For that WeakRefs might alleviate the issue but there are also other ways to solve this, without the need for WeakRefs. Another solution for cleaning up listeners which was not mention in the linked article is using AbortSignals. This also allows you to keep using anonymous functions: ```js const controller = new AbortController(); const {signal} = controller; button.addEventListener('click', () => { /*...*/ }, { signal }); button.addEventListener('mouseover', () => { /*...*/ }, { signal }); button.addEventListener('mouseout', () => { /*...*/ }, { signal }); // Sometime later... controller.abort(); // all listeners get removed ``` Related, perhaps, is #1296 which would allow you to get a signal from a Node when it is disconnected, which could simplify the above code to something like: ```js const signal = button.disconnectedSignal(); button.addEventListener('click', () => { /*...*/ }, { signal }); button.addEventListener('mouseover', () => { /*...*/ }, { signal }); button.addEventListener('mouseout', () => { /*...*/ }, { signal }); ``` -- Reply to this email directly or view it on GitHub: https://github.com/whatwg/dom/issues/1396#issuecomment-3138932602 You are receiving this because you are subscribed to this thread. Message ID: <whatwg/dom/issues/1396/3138932602@github.com>
Received on Thursday, 31 July 2025 07:58:46 UTC