I have some code that adds a mouseover event handler to svg circles to display tooltips. Should I remove/unbind these handlers when I remove the circle elements? I do not know if these handlers are attached to the svg object and I am afraid it may lead to shadow dom or memory leaks. See code below :
circles.enter().append("svg:circle")
.on("mouseenter", function(d) {
// show tooltip
});
circles.exit()
.on("mouseenter", null) // necessary?
.remove();
Removing the event listener first always results in lower memory usage (no leaks). Results: IE6 - memory leak.
TLDR; Always remove event listeners when you don't plan on using them any longer.
The main reason you should remove event listeners before destroying the component which added them is because once your component is gone, the function that should be executed when the event happens is gone as well (in most cases) so, if the element you bound the listener to outlasts the component, when the event ...
The removeEventListener() is an inbuilt function in JavaScript which removes an event handler from an element for a attached event. for example, if a button is disabled after one click you can use removeEventListener() to remove a click event listener.
I think you have your answer already but I was interested in how you show that this is true, at least in latest Chrome.
This is the section of the D3 code that removes DOM nodes:
function remove() {
var parent = this.parentNode;
if (parent) parent.removeChild(this);
}
export default function() {
return this.each(remove);
}
So as you can see it's depending on the browser to do cleanup of any associated listeners.
I created a simple stress test of adding/removing lots of circle nodes with D3:
var circles = svg.selectAll("circle")
.data(data, function(d) { return d.id; } );
circles.exit().remove();
circles.enter().append("circle")
.attr("id", function(d) { return d.id; })
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr( { r: 5, fill: 'blue' })
.on("mouseenter", function(d) { console.log('mouse enter') });
Live version here: http://bl.ocks.org/explunit/6413685
You will notice that the DOM node garbage collection counts correspond with the event listener garbage collection counts. In fact, you can't really tell them apart in the below screenshot since the lines are superimposed:
Note that for Internet Explorer, things are a little more complicated.
See also this article for more tips on tracking memory usage in Chrome tools.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With