简体   繁体   中英

Square grid exit selection in D3 v4

I have been working on changing this block to v4 with my limited exposure to d3js.

The changes are made are;

  • "https://d3js.org/d3.v3.js" to "https://d3js.org/d3.v4.js"

  • .ease('linear') to .ease(d3.easeLinear)

which i understood further from the change readme here .

The changes results in the chart not being able to reach the cell.exit.transition() block when I tried to console.log the exit function, this is also evident as the grids do not exit and just append from new randomized data:

cell.exit().transition()
    .delay(function(d, i) { return (n0 - i) * updateDelay; console.log(n0, n1);})
    .duration(updateDuration)
    .attr("width", 0)
    .remove();

From the readme, there is no change in the transition methods but I am thinking this is due to the change in the select function. I am having trouble seeing what when wrong as there seems to be no errors within the console when I run this.

The problem here seems to be the infamous magic behaviour that was introduced by Mike Bostock (D3 creator) in D3 v2, and later removed in D3 v4.

According to Bostock :

D3 2.0 introduced a change: appending to the enter selection would now copy entering elements into the update selection [...] D3 4.0 removes the magic of enter.append. (In fact, D3 4.0 removes the distinction between enter and normal selections entirely: there is now only one class of selection.)

You can read more about this issue in these answers: https://stackoverflow.com/a/47032222/5768908 and https://stackoverflow.com/a/45093007/5768908

In your case, the solution is changing the update selection to this:

var cellUpdate = cell.selectAll("rect")
    .data(d3.range(n1));

And then:

cellUpdate.exit()
    //etc...

cellUpdate.enter()
    .append("rect")
    //etc...

Here is the updated bl.ocks: https://bl.ocks.org/GerardoFurtado/b0d66087d9888a2cac3a42b114e5e8c4/72a0e54de5ce8cba2c398b282d953dd5c2bcc66e

PS: for this to work in v4/5 (but not from v5.8 onwards) you have to change the text tween as well:

.tween("text", function() {
    var self = this;
    var i = d3.interpolateNumber(n0, n1);
    return function(t) {
        self.textContent = formatNumber(Math.round(i(t)));
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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