本文介绍了d3回调函数.remove()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道当我的所有行被删除,所以我可以调用另一个函数。

I'd like to know when all my lines are removed so I can call another function.

svg.selectAll('line').transition().duration(2500)
    .style("stroke-opacity",0).remove();

我知道我可以使用.each(end,mycallback)在每次转换后运行一个回调,但我只想在所有转换完成后运行一次。

I know I can run a callback after each transition using .each("end",mycallback), but I only want to run it once when all transitions are done.

如果我尝试这个

svg.selectAll('line').transition().duration(2500)
   .style("stroke-opacity",0).remove().call(function(){console.log("yes");});

那么.call()会在转换完成之前发生。

then the .call() happens before the transition is done.

我可以添加一个window.setTimeout(),但是有正确的方法吗?

I could add a window.setTimeout(), but is there a correct way to do this?

推荐答案

p>正确的方法是使用 .each(end,callback)。正如你所指出的,这对于转换中的每个元素调用一次。您无法更改此设置,但可以添加一个计数器,记录已删除的元素数量:

The correct way to do it is to use .each("end", callback). As you point out, this is called once for each element in the transition. You can't change this, but you can add a counter that keeps track of how many elements have been removed:

d3.selectAll("div")
  .call(setupRemove)
  .transition().duration(500)
  .each("end", onRemove)
  .remove();

function setupRemove(sel) {
  counter = sel.size();
}
function onRemove() {
  counter--;
  if(counter == 0) {
    console.log("all done");
  }
}

完成演示。请注意,在特殊情况下,当您想在第一个集合完成时运行另一个转换,您可以再次使用 .transition()

Complete demo here. Note that in the special case when you want to run another transition when the first set is finished, you can use just .transition() again.

这篇关于d3回调函数.remove()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:38