Reputation: 13710
Im just getting started on d3.js and was going through Nick's source code on github here and got stuck at the part where he is passing a function as data into d3.js.
The var x
in the function assigned to next var
gets incremented from 0 to the loop counter
as i show in the jsbin link below. I cant quite wrap my head around how x gets incremented automatically and how does it know the loop counter that it needs to get incremented upto everytime.
the
next variable
is called from >>newdata
from the >>render function
?
I just setup a jsbin here
Upvotes: 1
Views: 255
Reputation: 25157
First, for simplification, this
var selection = d3.select("#container").selectAll("div")
.data(newData); // <- D
is just like writing
var arrayOfFunctions = newData();
var selection = d3.select("#container").selectAll("div")
.data(arrayOfFunctions); // <- D
So, for example, calling this code 3 times (via setInterval) builds up arrayOfFunctions
like this:
arrayOfFunctions = [
function (x) { return 15 + x * x; },
function (x) { return 15 + x * x; },
function (x) { return 15 + x * x; }
]
(Note: it's not literally like that, because in actuality they're just pointers to the same function next
)
So nothing about that increments x
. But once it binds those functions to DOM elements (via data(arrayOfFunctions)
and runs through this bit:
selection.attr("class", "v-bar")
.style("height", function (d, i) {
return d(i) + "px"; // <- E
})
d
is function (x) { return 15 + x * x; }
and i
(which is 0, 1, or 2) is passed in as x
to that function when it calls d(i)
.
And that's what essentially increments x
.
Upvotes: 2
Reputation: 108512
This part:
.data(newData);
is simply going to call the newData
function and bind the return to the selection.
So each call to render
in the setInterval
simply pushes the next
function into his data
array.
This part then:
selection.attr("class", "v-bar")
.style("height", function (d, i) {
return d(i) + "px"; // <- E
})
.select("span")
.text(function(d, i){
return d(i); // <- F
});
Calls d
which is the next
function for each element in the data array. It's passing the index position in the data
array.
So the first render
call is:
15 + 0 * 0;
Second is:
15 + 0 * 0;
15 + 1 * 1;
Third is:
15 + 0 * 0;
15 + 1 * 1;
15 + 2 * 2;
Upvotes: 2