d3.js should I detach event listener on exit/remove?

前端 未结 1 772
一向
一向 2021-01-17 16:51

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 kn

相关标签:
1条回答
  • 2021-01-17 17:10

    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

    1. Open the above with latest Chrome
    2. Open the Developer Tools
    3. Click the Timeline tab
    4. Click the Record button at the bottom
    5. Let it run for a couple minutes, then click the button again to stop recording
    6. Drag the selector in the top timeline view to cover several of the garbage collection sawtooth patterns

    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:

    Chrome Screenshot

    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.

    0 讨论(0)
提交回复
热议问题