I am currently reading "Data Visualization with D3 4.x Cookbook Second Edition".The data update mode is mentioned in chapter3.Sometimes the author uses merge() to achieve data update, but sometimes the author uses selectAll() to achieve. I have found that in some cases they are not interchangeable. I'm confused right now and I want to know, how can I determine which way I should do in data update.
In the 3.2.2,the author uses merge() to achieve data update
function render(data) { // <- B
var bars = d3.select("body").selectAll("div.h-bar") // <- C
.data(data); // Update <- D
// Enter
bars.enter() // <- E
.append("div") // <- F
.attr("class", "h-bar") // <- G
.merge(bars) // Enter + Update <- H
.style("width", function (d) {
return (d * 3) + "px"; // <- I
})
.text(function (d) {
return d; // <- J
});
// Exit
bars.exit() // <- K
.remove();
}
In the 3.6.2,the author uses selectAll() to achieve data update
function render(data, category) {
var bars = d3.select("body").selectAll("div.h-bar") // <-B
.data(data);
// Enter
bars.enter()
.append("div") // <-C
.attr("class", "h-bar")
//.merge(bars)
.style("width", function (d) {
return (d.expense * 5) + "px";}
)
.append("span") // <-D
.text(function (d) {
return d.category;
});
// Update
d3.selectAll("div.h-bar").attr("class", "h-bar");
// Filter
bars.filter(function (d, i) { // <-E
return d.category == category;
})
.classed("selected", true);
}
I really need your help! Thanks!