D3:几乎相同的代码,不同的结果

D3: almost identical codes, different results

我正在尝试应用 this 建议来捕捉多个转换的结束。 但是在我的本地文件中出现 Uncaught TypeError: t.call is not a function 错误。代码如下:

    var svg = d3.select('svg');

  function endall(transition, callback) { 
    if (typeof callback !== "function") throw new Error("Wrong callback in endall");
    if (transition.size() === 0) { callback() }
    var n = 0; 
    transition 
        .each(function() { ++n; }) 
        .each("end", function() { if (!--n) callback.apply(this, arguments); }); 
  } 


for (var i=0;i<5;i++) {

    svg.append('rect')
            .attr("x",i*60)
      .attr("y",50)
      .attr("height",50)
      .attr("width",50)
      .style("fill","#ff0000");
}

    svg.selectAll("rect:not(.active)")
      .transition()
      .duration(1000)
      .style("fill","#00ff00")
      .call(endall, function() { alert("all done") });

当我在没有 D3 模板的情况下将其移植到 jsfiddle using a D3 template, it works well. On the other hand, when I port it on jsfiddle 时,我得到了同样的错误。

显然我遗漏了什么,但我无法理解是什么。

未产生错误的 fiddle 在 v3 上运行,而产生错误的在 v5 上运行。

在 d3v3 中,您可以对事件使用 transition.each("end",...)

transition.each([type, ]listener)

If type is specified, adds a listener for transition events, supporting "start", "end" and "interrupt" events. The listener will be invoked for each individual element in the transition. (v3 docs)

在 d3v4 和 v5 中,此方法已替换为 transition.on("end",...) 事件:

selection.on(typenames[, listener[, options]]) <>

Adds or removes a listener to each selected element for the specified event typenames. (current docs)

transition.each(function) 仍可用于对正在转换的每个项目执行操作,但不能用于事件侦听。由于版本之间的这种变化,您会得到一个错误,即 t.call 不是一个函数(它是一个字符串:"end"),并且永远不会触发警报。

对于 d3v4 或 d3v5,改为使用:

transition 
    .each(function() { ++n; }) 
    .on("end", function() { if (!--n) callback.apply(this, arguments); }); 

Updated fiddle.