In d3, what does the .data ([]) construct do. Exit (). Remove () means?

I am guessing that .selectAll('.my_class').data([]).exit().remove()

as part of the call chain d3 removes non-data elements with css class my_class

, but the syntax puzzled me. The intention is to simply clear the deck by removing all the elements.

It is impossible to disassemble it.

+3


source to share


1 answer


It's hard to explain if you don't already understand I / O / O and data binding. I will do my best to help. This page should also explain, in particular, the incoming and outgoing sections.

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

Let's start by typing. If we assume you have an svg element that does not contain 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 it does is select all the environment items in the svg element (which we said they weren't) and their associated data. Since there are 4 elements in the dataset, d3 indicates that 4 elements have been added. Calling .enter()

and .append('circle')

returning these elements to reality, and calling .attr('r', function(d) { return Math.sqrt(d); });

sets their radius to the root of the associated data value.

Now let's answer your question. We now have 4 circle elements, each with associated data. If we were to execute the above code again with another array of 4 integers, no new circles would be added. The reason is that 4 circles are selected, there is an array of length 4, resulting in a net difference of 0. However, what happens is the new data is bound to the elements of the circle. That is, the radius of the circles will change.



What if we run this:

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

      

we select 4 circles by binding an empty array to them, which means there are 4 too many circle elements. While a selection .enter()

contains additional items to add, a selection .exit()

contains items to remove.

So we select 4 circles without associating anything with them, calling .exit()

which contains all 4 circles and deletes them.

You are correct in thinking that it clears the deck by removing everything with class "my_class" from the page.

Hope it helps.

+6


source







All Articles