Reputation: 12305
Can someone explain like i'm 5 how this D3 syntax actually works?
var link = svg.selectAll('.link')
.data(links)
.enter().append('line')
.attr('class', 'link');
What it seems to do is just append links to the tree.
But how I read that is "select everything that is of class link, and append an attribute class=link". How it can select before those exist is puzzling.
Why is there a "select" before the items actually exist? Does select really mean "insert"?
Upvotes: 4
Views: 3559
Reputation: 20830
I agree that it is totally confusing to have to make a selection before it even exists. BUT by calling data(someDataArray)
on the selection, this placeholder selection is now bound to your data.
Now, for everything that will enter
the data
in someDataArray
, d3 will append
a corresponding SVG line
(and attach the relevant data).
If someDataArray
changes, d3 can change the appearance of the attached SVG node with update
or even remove the old node that no longer has associated data with exit
.
Upvotes: 2
Reputation: 32327
Line by line analysis would like below:
Select all the DOMs having class link
.
var link = svg.selectAll('.link')
To all those links bind the data. Here data links is an array.
links[0]
is bound to first DOM if present.
links[1]
is bound to second DOM if present.
..so on
.data(links)
.enter()
Case 1: If the array links has 2 elements and the selection DOM elements has 0 elements. Then 2 line DOM will be appended to the svg DOM.
Case 2: If the array links has 2 elements and the selection DOM elements has 1 element. Then 1 new line DOM will be appended to the svg DOM.
Case 3: If the array links has 2 elements and the selection DOM elements has 2 or more elements. Then 0 new line DOM will be appended to the svg DOM.
.append('line')
.attr('class', 'link');
This would be a good read
Upvotes: 4