0

Does jQuery's .empty() method remove the listeners attached via

var e = () => { ... };
element.addEventListener('click', e);

as well or just the ones attached via

var e = () => { ... };
$(element).on('click', e);

I'm thinking about memory leaks here: If I have dynamically created elements within the DOM, which also have event listeners attached and I'd like to remove these elements from the DOM again - do I

  • either have to remove every single listener from every node I'd like to remove by hand using removeEventListener()
  • or have to use a library like jQuery to both add and remove listeners using .on() and .empty() respectively?

As far as I understood this question, dynamically adding and removing elements which have event listeners does not clean up all references and therefore causes those elements to remain in memory.

var element = document.createElement('div');
var handler = function() {
    alert('foo');
};

document.body.appendChild(element);

// Option 1
element.addEventListener('click', handler);
document.body.innerHTML = '';

// Option 2
element.addEventListener('click', handler);
$(document.body).empty();

// Option 3
$(element).on('click', handler);
$(document.body).empty();

Which option entirely removes the element not only from the DOM but completely frees its memory? Using removeEventListener unfortunately is not practical for me ...

mrsubwoof
  • 183
  • 1
  • 11

1 Answers1

2

empty() removes the child elements from the parent(s). Any event listeners attached to the elements will no longer exist, as the children will no longer exist.

Also: https://api.jquery.com/empty

To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.

If you want to remove elements without destroying their data or event handlers (so they can be re-added later), use .detach() instead.

jQuery also cleans up after itself if it knows elements are being destroyed.

However, none of this guarantees that there are still not variable references to the elements in your javascript, which would cause them to not be garbage collected. Neither empty() nor removing the event listeners yourself would cause the element, itself, from being garbage collected. You would have to ensure that your logic no longer has references to the elements being removed.

Community
  • 1
  • 1
Taplar
  • 24,788
  • 4
  • 22
  • 35
  • Thank you very much for your answer. Unfortunately, I'm not sure if I understood this point correctly: Does `.empty()` remove _all_ event handlers (those attached via `.addEventListener()`) or just the ones attached using jQuery's `.on()`? – mrsubwoof Mar 19 '19 at 11:00
  • `empty()` does not have to destroy the event handlers attached with `addEventListener()`. addEventListener attaches the listeners **on the element**. When the element is destroyed, by association, the listeners are as well. @mrsubwoof – Taplar Mar 19 '19 at 11:21