最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing Object function into data() in d3 - Stack Overflow

programmeradmin2浏览0评论

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?

http://bl.ocks/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?

Share Improve this question edited Nov 26, 2020 at 15:34 peterh 1 asked Jul 23, 2013 at 23:40 daikonradishdaikonradish 7026 silver badges16 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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.

发布评论

评论列表(0)

  1. 暂无评论