Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

d3.js - Can enter() selection be reused after append/insert?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...