Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In d3 what does the construct .data([]).exit().remove() mean?

Tags:

d3.js

I presume that .selectAll('.my_class').data([]).exit().remove() as part of a d3 call chain removes non-data bound elements with css class my_class but the syntax has me baffled. Is the intent to simply clear the deck, removing all elements.

Can't parse it.

like image 678
dugla Avatar asked Sep 09 '26 02:09

dugla


1 Answers

This is hard to explain if you don't already understand enter/update/exit and data binding. I'll do my best to help. This page should explain a lot as well, specifically the entering and exiting sections.

http://bost.ocks.org/mike/circles/

Lets begin with entering. If we assume you have an svg element that contains no circle elements, we can add 4 like so:

svg.selectAll('circle')
  .data([32, 57, 112, 293])
  .enter()
  .append('circle')
  .attr('r', function(d) { return Math.sqrt(d); });

What this does is selects all circle elements in the svg element (which we said there are none) and bound data to them. Since there are 4 elements in the data array, d3 figures out that there are 4 elements to be added. The call to .enter() and .append('circle') bring these elements into reality, and the call to .attr('r', function(d) { return Math.sqrt(d); }); sets their radius to the root of the value of the bound data.

Now lets answer your question. We now have 4 circle elements, each of which have bound data associated with them. If we were to run the above code again with a different array of 4 integers no new circles would be added. The reason being that 4 circles are selected, there is an array of length 4 passed in, so the net difference is 0. What does happen, however, is new data would be bound to the circle elements. I.e. the radius of the circles would change.

What if we were to run this:

svg.selectAll('circle')
  .data([])
  .exit()
  .remove()

we are selecting the 4 circles, binding an empty array to them, which means that there are 4 too many circle elements. Whereas the .enter() selection contains the extra elements to add, the .exit() selection contains the elements to remove.

Therefore, we are selecting 4 circles, binding nothing to them, calling .exit(), which contains all 4 circles, and removing them.

You are correct in assuming that it clears the deck, removing everything with the class 'my_class' from the page.

Hope that helps.

like image 65
lhoworko Avatar answered Sep 13 '26 05:09

lhoworko