Reputation:
The problem is with d3 js, enter method. Following are the steps and outcome.
I add a couple of circles to svg using data(source).enter()
. I got the exact number of circles.
The datasource changes and the new datasource has less number of elements. So I use exit to remove excessive circles. This as well, works like a charm. Additional circles are removed.
circles.data(source2).exit().remove();
The datasource changes again and this time it has more elements than source2. In this case, I use data(source3).enter()
to add additional circles. But this never happens.
Here's a fiddle with a crude reconstruction of the problem. http://jsfiddle.net/tejasj/z59mgb03/1/
UPDATE: A new fiddle with comments in the code.
Upvotes: 3
Views: 3080
Reputation: 109232
There are two main problems with your code. One is that instead of using the same selection for enter/update/exit, you're using different selections with the same selector. That is, your code looks like this:
circles.data(...).enter()...
circles.data(...).exit()...
This will match data several times (each time you call .data()
) and won't achieve the result you're looking for as the state (i.e. the DOM) changes between the calls to .data()
. That is, you're matching the data once, getting the enter selection and appending elements. Now when you're matching the data there will be different elements and the matching will do something different.
The proper pattern to operate on multiple selections is to save the selection:
var sel = circles.data(...);
sel.enter()...
sel.exit()...
The second problem is that you're operating on circles
, which contains the "frozen" view of the DOM after you added the first set of circles. This won't reflect the actual DOM as soon as you make any updates to it. Explicitly select the elements you want instead:
var sel = svg.selectAll("circle").data(...);
sel.enter()...
Taken together, these two things are messing up the way D3's data matching mechanism works completely and you're getting something completely different from what you expect. Complete demo with fixes here.
Upvotes: 4