ankakusu
ankakusu

Reputation: 1828

Updates and enters in D3JS

I have a 4 element data set and append those data to a div in my page(refer to the code below).

Question 1) The statically entered "p" of "I was already here" remained as is. However, I expected it to be updated in "1".

Question 2) When I reenter the data to the html, I expected a result as 1, 2, 3, 4, 1, 2, 3, 4. However, the output is I was already here, 2, 3, 4, 2, 3, 4. Why does the first element(1) of the data array skipped when data is reentered?

Do you have any idea?

Here is the body of my html file:

<div><p>I was already here</p></div>

This is my javascript code:

var data = [ 1, 2, 3, 4 ]
var svg = d3.select("body");
var paragraphs = svg.select("div").selectAll("p").data(data);
// data added
paragraphs.enter().append("p").text( function(d) { return d; });
// new items are added.
paragraphs.enter().append("p").text( function(d) {return d;});

Output is as follows:

I was already here

2

3

4

2

3

4

You can find the jsfiddle here.

Upvotes: 0

Views: 59

Answers (1)

kalley
kalley

Reputation: 18462

When you call enter, it only works for new elements. Since you have the one '

' there originally, nothing is happening. One way to manage this would be to do something like:

// this adds the paragraphs that are missing
paragraphs.enter().append('p');

// This will update all text
paragraphs.text(function(d) { return d; });

If you want it to give you 1 2 3 4 1 2 3 4, you're going to run into some issues since the first element exists already, so you'd end up with 1 2 3 4 2 3 4. You'll have to make your data set bigger, which can be done easily using concat like so:

var paragraphs = svg.select("div").selectAll("p").data(data.concat(data));

Here's an updated fiddle


You can think of it kind of like this:

  • Your selectAll is going to get all existing ones.
  • enter will do stuff to anything that is new, ie everything greater than the first <p>
  • calling text on paragraphs after you've done the enter is an updating all elements

When you called enter again, it was again only going through the missing ones, which is why you were only getting 2 - 4.

I hope that helps.

Upvotes: 2

Related Questions