d3.js我应该在exit / remove上分离事件监听器吗? [英] d3.js should I detach event listener on exit/remove?

查看:263
本文介绍了d3.js我应该在exit / remove上分离事件监听器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码可以将鼠标悬停事件处理程序添加到svg界面来显示工具提示。我删除/取消绑定这些处理程序时,我删除圆圈元素?我不知道这些处理程序是否附加到svg对象,我恐怕可能会导致shadow dom或内存泄漏。请参阅下面的代码:

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


解决方案

我想你有你的答案,但我有兴趣至少在最新的Chrome中,您如何表现出这一点。



这是。



另请参见<有关跟踪Chrome工具中内存使用情况的更多提示,请本文


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();

解决方案

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:

  d3_selectionPrototype.remove = function() {
    return this.each(function() {
      var parent = this.parentNode;
      if (parent) parent.removeChild(this);
    });
  };

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:

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.

这篇关于d3.js我应该在exit / remove上分离事件监听器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆