Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can enter() selection be reused after append/insert?

Tags:

d3.js

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?

like image 944
Scott Cameron Avatar asked May 29 '12 23:05

Scott Cameron


1 Answers

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");
like image 155
mbostock Avatar answered Nov 16 '22 20:11

mbostock