I have a scenario where I want to use a data join to append 2 new elements for each data element.
I was originally doing something like this:
var y = d3.selectAll("line")
.data([123, 456]);
y.enter().append("line"); // assume attr and style set
y.enter().append("line");
y.transition()...
Before I thought it through, I was expecting that the update selection used in my transition would contain the merged appends from the enter selection. But of course this did not work because there's only 1 slot in the selection per data element.
So I changed the code such that it still used the same enter() selection twice but then reselected for the new elements in order to do the transition.
This approach worked, but my question is whether or not this is a recommended way to go about things. Should I make sure to stop using enter() after I append/insert? Or is it OK do use it to create multiple elements as long as I remember that the update selection will only contain the elements created last?
If it does turn out that this is wrong, what is a better way to achieve this?
No. The purpose of the data-join is to synchronize elements with data, creating, removing or updating elements as necessary. If you create elements twice, the elements will no longer correspond one-to-one with the bound array of data.
If you want two elements to correspond to each datum, then append a group (G) element first to establish a one-to-one mapping from data to elements. Then append child elements as necessary. The resulting structure is like this:
<g>
<line class="line1"></line>
<line class="line2"></line>
</g>
<g>
<line class="line1"></line>
<line class="line2"></line>
</g>
For example:
var g = svg.selectAll("g")
.data([123, 456]);
var gEnter = g.enter().append("g");
gEnter.append("line").attr("class", "line1");
gEnter.append("line").attr("class", "line2");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With