简体   繁体   中英

D3's use of the 'select' and 'selectAll'

I cannot wrap my head around D3's select statement.

When creating a graph, you would typically do something like this:

svg.selectAll("rect")
  .data(my_graph_data)
  .enter()
  .append("rect")
  ..//etc.

What I don't understand is the selectAll. At this point in time, there is NO element to select! The elements are only appended later based on the data.

Or should I read these kind of D3 statements from right to left? In that case, why would I need to select the elements?

You need to select the (non-existant) elements because of the subsequent call to .data() . This call instructs D3 to match the data given in the argument to the elements you've selected. If, as in your case, the selection is empty, D3 will create placeholder elements for all of them -- the enter selection. This selection you can then use, as you do, to append new elements.

This .selectAll(...).data(...) pattern is consistent regardless of what you have in your SVG already. As long as you handle all three (enter, update, exit) selections, it will always do the expected thing. In the initial selection, there may be no elements, elements for all of the data, or somewhere in between.

Technically, you don't have to use this pattern when adding new elements initially, it just makes the code more consistent. In particular, you can use this pattern in a function that will update the SVG with new data, regardless of its state (ie works the same way initially and when getting and displaying new and changed data).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM