Basic D3: Why Can You Select Things That Don't Exist Yet?
Solution 1:
Although, at first sight, this may look like a simple and silly question, the answer to it is probably the most important one for everyone trying to do some serious work with D3.js. Always keep in mind, that D3.js is all about binding data to some DOM structure and providing the means of keeping your data and the document in sync.
Your statement does exactly that:
Select all elements having class
node
. This may very well return an empty selection, as it is in your case, but it will still be ad3.selection
.Bind data to this selection. Based on the above mentioned selection this will, on a per-element basis, compute a join checking if the new data is a) not yet bound to this selection, b) has been bound before, or c) was bound before but is not included in the new data any more. Depending on the result of this check the selection will be divided into an enter, an update, or an exit selection, respectively.
Because your selection was empty in the first place. All data will end up in the enter selection which is retrieved by calling
selection.enter()
.You are now able to append your new elements corresponding to the newly bound data by calling
selection.append()
on the enter selection.
Have a look at the excellent article Thinking with Joins by Mike Bostock for a more in-depth explanation of what is going on.
Post a Comment for "Basic D3: Why Can You Select Things That Don't Exist Yet?"