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 ...