了解过D3的同窗,对下边的这张图片想必都很熟悉

D3是data-diven-document的意思,那么到底什么是数据驱动文档呢?D3是怎样把数据跟dom元素链接到一块儿的?
-
通常是分为三步:express
- selectAll 选取
- data 绑定
- 经过enter() update() exit() 操做
- 就像下边的代码所示:
svg.selectAll("circle") //return empty selection
.data(data) // 跟一个数组绑定,返回update selection
.enter() //返回enter selection
.append("circle") //
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", 2.5);
- 下面咱们仔细的看一下D3的select和data join
selection
- 通常来讲,你可能会认为selection是包含dom元素的数组,其实这是错误的。selection是array的子类,它包含了操作选中元素的方法,好比:attr style;并继承了array的方法。
- selection是数组的数组。d3.select和d3.selectAll都返回的是把包含一个group数组的数组,而selection.selectAll返回包含多个group的数组。

数据绑定 (data join)
- 当你给selectin绑定数据,实际上data是存储在selection中每个dom元素的__data__属性上。
d3.select('body').__data__ = 42 等价于
d3.select('body').datum(42)
d3.select('body').datum(42).append('h1') //h1继承了父级的数据
什么是D3中的data?
- data就是包含值的数组。
- data数组中的值是跟selection中的group对应的,而不是跟group中的元素。(selection.data defines data per-group rather than per-element: data is expressed as an array of values for the group, or a function that returns such an array. Thus, a grouped selection has correspondingly grouped data!)
数据绑定中的key
- 默认是经过比较datum和element的index来绑定的。

- 另外咱们还能够指定一个key函数,自定义key pair。

- 须要注意:key 函数是每一个group中的each element执行一次,而不是整个group来对比。

enter update exit
- 若是selection和data中的key匹配不上,那么就有了上述三个selection
- 注意上述三个selection中未匹配的元素用null表示

Merging Enter & Update
- enter.append有一个反作用:把update中的null元素替换成enter中新建立的元素
这样整个数据绑定和选择的过程大体就是这样。
本文中的内容,基本是[https://bost.ocks.org/mike/se...]这篇文章中讲的,我把它整理了一下,加了点本身的理解。若是有不明白的地方,原文讲的更加细致。数组