I'm struggling with understanding the merge function in D3, despite reading through the D3 API countless times.
The API says: "This method is commonly used to merge the enter and update selections after a data-join. After modifying the entering and updating elements separately, you can merge the two selections and perform operations on both without duplicate code."
Here's an example of the supposedly straightforward use of it, in a force directed chart, where the ticked function is called with every tick:
var simulation = d3.forceSimulation(nodes)
.force("charge", chargeForce)
.force("center", centerForce)
.on("tick", ticked);
function ticked() {
var u = d3.select("svg").selectAll("circle").data(nodes)
u.enter().append("circle").attr("r",5)
.merge(u) // What is the merge function doing here?
.attr("cx", d => d.x)
.attr("cy", d => d.y)
u.exit().remove() // Why is it necessary to remove excess objects w/ the exit selection?
}
I understand how data-binding works, and how enter() and exit() selections work. However, I've never had to use a "merge" before, and I don't understand it is doing here. If someone could briefly walk through what is going on in this function step-by-step, that would be extremely useful. I'm sure others have similar questions.
The documentation explains very well what that function does, so what it does is instead of you having to do this
u.attr("cx", d => d.x)
.attr("cy", d => d.y);
u.enter().append("circle").attr("r",5)
.attr("cx", d => d.x)
.attr("cy", d => d.y);
You can just call attr
once like
u.enter().append("circle").attr("r",5)
.merge(u) // after this point, any updates will apply to both u and u.enter() selections
.attr("cx", d => d.x)
.attr("cy", d => d.y)
It will set attributes cx
and cy
on both u
-the update selection and u.enter()
-the enter selection
Why is it necessary to remove excess objects w/ the exit selection?
Because the exit selection contains any extra DOM elements that were not bound to the elements in the array you passed to data()
, you can do whatever you need on the exit colllection, for example setting the styles by calling u.exit().style(...)
, etc. instead of calling remove
to delete them from the DOM