Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Object function into data() in d3

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?

like image 324
daikonradish Avatar asked Jul 23 '13 23:07

daikonradish


1 Answers

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.

like image 148
roippi Avatar answered Oct 12 '22 07:10

roippi