简体   繁体   English

d3.js我应该在退出/删除时分离事件监听器吗?

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

I have some code that adds a mouseover event handler to svg circles to display tooltips. 我有一些代码,将鼠标悬停事件处理程序添加到svg圈子中以显示工具提示。 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. 我不知道这些处理程序是否已附加到svg对象,并且恐怕可能导致影子dom或内存泄漏。 See code below : 参见下面的代码:

circles.enter().append("svg:circle")
   .on("mouseenter", function(d) {
      // show tooltip
   });
circles.exit()
   .on("mouseenter", null) // necessary?
   .remove();

I think you have your answer already but I was interested in how you show that this is true, at least in latest Chrome. 我认为您已经有了答案,但我对您如何证明这是正确的(至少在最新的Chrome浏览器中)很感兴趣。

This is the section of the D3 code that removes DOM nodes: 这是D3代码中删除DOM节点的部分:

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: 我创建了一个简单的压力测试,使用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 此处的实时版本: http//bl.ocks.org/explunit/6413685

  1. Open the above with latest Chrome 使用最新的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. 您会注意到DOM节点的垃圾收集计数与事件侦听器垃圾收集计数相对应。 In fact, you can't really tell them apart in the below screenshot since the lines are superimposed: 实际上,由于这些行是重叠的,因此您无法在下面的屏幕截图中真正区分它们:

Chrome屏幕截图

Note that for Internet Explorer, things are a little more complicated . 请注意,对于Internet Explorer, 事情要复杂一些

See also this article for more tips on tracking memory usage in Chrome tools. 另请参阅本文,以获取有关在Chrome工具中跟踪内存使用情况的更多提示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM