D3在转换结束时插入条件

时间:2015-06-29 21:24:41

标签: javascript d3.js

我正在调整以下代码,在每次转换结束时重绘一行。

function tick() {

// push a new data point onto the back
data.push(random());

// redraw the line, and slide it to the left
path
    .attr("d", line)
    .attr("transform", null)
  .transition()
    .duration(500)
    .ease("linear")
    .attr("transform", "translate(" + x(-1) + ",0)")
    .each("end", tick);

// pop the old data point off the front
data.shift();

}

代码来源:https://gist.github.com/mbostock/1642874

但是,我不想在每次转换结束时自动重新调用tick(),而是想检查某个布尔值(myVar)是否为真,并且仅在这种情况下重新调用tick()。

我试图写这样的东西,但tick()函数已经停止被重新调用。有人可以帮我理解错误。感谢。

function tick() {

// push a new data point onto the back
data.push(random());

myVar = true //for now just hardcoding the value of myVar

// redraw the line, and slide it to the left
path
    .attr("d", line)
    .attr("transform", null)
  .transition()
    .duration(500)
    .ease("linear")
    .attr("transform", "translate(" + x(-1) + ",0)")
    .each("end", function() { if (myVar === true) return tick;});

// pop the old data point off the front
data.shift();

}

注意:新代码改编自JesperWe的回答:Invoke a callback at the end of a transition

1 个答案:

答案 0 :(得分:1)

在您的示例中,您替换tick的功能是:

function() { if (myVar === true) return tick;}

但是,D3不会对该返回值执行任何操作。相反,你应该把它写成:

function() { if (myVar === true) tick();}

所以当D3调用该函数时,你可以在你传递的函数内有条件地调用tick

相关问题