什么时候绑定到其子级可用的父级数据? [英] When is data bound to a parent available to its children?

查看:95
本文介绍了什么时候绑定到其子级可用的父级数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下,我已经能够将我的数据绑定到父元素(例如,< svg> 容器),然后追加子< path> 元素,然后使用数据更新其 d 属性。

On certain occasions I have been able to bind my data to a parent element (say, the <svg> container), then append child <path> elements, and then update their d attributes with the data. Other times, it seems I can't do this.

例如,在我的代码中,我有

For example, in my code I have

var svg = d3.select(this).selectAll("svg").data([allSeries]);

其中 allSeries 是一个3元素数组的我的三个时间序列数据。然后为每个元素添加一个路径

where allSeries is a 3-element array of my three time series data. I then add a path for each element.

var gEnter = svg.enter().append("svg").append("g");
for (var i = allSeries.length - 1; i >= 0; i--) {
  gEnter.append("path").attr("class", "line").style("opacity", 0);
};

后来,当要添加/更新数据时,我尝试过

Later, when it's time to add/update the data, I tried this

g.selectAll(".line")
   .attr("d", function(d) { return line(d.values); })

但它不工作。

g.selectAll(".line")
   .data(allSeries)
   .attr("d", function(d) { return line(d.values); })

那么,如何让我的 .line 元素从 svg ?中读取数据?

So how can I get my .line elements to read the data from svg?

推荐答案

嵌套组需要声明它的数据源作为身份函数,才能访问父组的子元素:

The nested group needs to declare it's data source as the identity function in order to have access to the child elements of the parent group:

g.selectAll(".line")
   .data(function(d) {return d;})
   .attr("d", function(d) { return line(d.values); })

在以下文档中更好地解释了selection.data()函数的文档: https://github.com/mbostock/d3/wiki/Selections#wiki-data

This is better explained in the documentation of the selection.data() function here: https://github.com/mbostock/d3/wiki/Selections#wiki-data


例如,您可以将二维数组绑定到初始选择,然后将包含的内部数组绑定到每个子选择。在这种情况下,值函数是identity函数:它为每个子元素组调用,传递绑定到父元素的数据,并返回这个数组。

For example, you may bind a two-dimensional array to an initial selection, and then bind the contained inner arrays to each subselection. The values function in this case is the identity function: it is invoked for each group of child elements, being passed the data bound to the parent element, and returns this array of data.

这篇关于什么时候绑定到其子级可用的父级数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆