在d3.js新版本(V5)中增加了selection.join方法大大簡化了數據的update,enter,exit。
selection.join案例鏈接:https://observablehq.com/@d3/selection-join
看下面案例
const matrix = [
[11975, 5871, 8916, 2868],
[ 1951, 10048, 2060, 6171],
[ 8010, 16145, 8090, 8045],
[ 1013, 990, 940, 6907]
];
d3.select("body")
.append("table")
.selectAll("tr")
.data(matrix)
.join("tr")
.selectAll("td")
.data(d => d)
.join("td")
.text(d => d);
數據是一個多維數組,然後生成一個表格,如果用之前的enter的方式,則需要更加複雜的代碼,先生成tr,再生成td。當數據發生變化的時候,就更難操作了。有了join方式,就可以無視這些問題了。
如果想定義不同的enter,和update方法,用join也可以實現的。參考下面的代碼,分別再join中定義enter\update\exit的方法。
svg.selectAll("text")
.data(randomLetters(), d => d)
.join(
enter => enter.append("text")
.attr("fill", "green")
.attr("x", (d, i) => i * 16)
.attr("y", -30)
.text(d => d)
.call(enter => enter.transition(t)
.attr("y", 0)),
update => update
.attr("fill", "black")
.attr("y", 0)
.call(update => update.transition(t)
.attr("x", (d, i) => i * 16)),
exit => exit
.attr("fill", "brown")
.call(exit => exit.transition(t)
.attr("y", 30)
.remove())
);