http://bl.ocks.org/mbostock/1134768
I am learning it to use d3 to render data. I'm trying to understand what's going on in the code above, in particular, in the snippet:
// Add a rect for each date
var rect = cause.selectAll("rect")
.data(Object) // THIS IS WEIRD TO ME....
.enter().append("svg:rect")
.attr("x", function(d) { return x(d.x); })
.attr("y", function(d) { return -y(d.y0) - y(d.y); })
.attr("height", function(d) { return y(d.y); })
.attr("width", x.rangeBand());
What's the Object constructor doing in .data()
? I think that data()
will force the evaluation of a function, so in effect an object is being created? Why is this needed to insert a rectangle for each element of each array in causes
?
See this answer.
It is being used as an identity function - what was bound to the selection before, remains bound. This pattern is generally necessary because you have to call .data()
to get the update selection.
Personally I strongly dislike obfuscating my code like this; I would much rather do .data(function(d) { return d;})
as it is obvious what I'm doing there. YMMV.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With