博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
理解D3中的数据连接(data join)和选取(selection)是怎么工作的
阅读量:7209 次
发布时间:2019-06-29

本文共 1514 字,大约阅读时间需要 5 分钟。

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

D3是data-diven-document的意思,那么到底什么是数据驱动文档呢?D3是怎样把数据跟dom元素连接到一起的?

  • 一般是分为三步:

    • 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中新创建的元素

这样整个数据绑定和选择的过程大致就是这样。

本文中的内容,基本是[]这篇文章中讲的,我把它整理了一下,加了点自己的理解。如果有不明白的地方,原文讲的更加细致。

转载地址:http://zblum.baihongyu.com/

你可能感兴趣的文章
[转载]浅析jQuery框架与构造对象
查看>>
微信小程序基本入门
查看>>
oracl 数字型函数
查看>>
Q443 压缩字符串
查看>>
Bootstrap——网站添加字体图标
查看>>
MVC传递数据-传递对象或对象集合
查看>>
单页应用的三大优势及监控方法
查看>>
菜鸟调错(三)——Jboss与jdk版本号不兼容导致WebService调用出错
查看>>
你是那种仅仅看《XXXXX从入门到精通》的程序猿吗?
查看>>
Python开发【第一篇】:目录
查看>>
《新闻发布》解析
查看>>
C++知识点
查看>>
FTP传输文件被破坏的问题(Linux、Busybox)
查看>>
242. Valid Anagram
查看>>
P1024 一元三次方程求解(二分答案)
查看>>
Collections库使用
查看>>
SQL Server开启READ_COMMITTED_SNAPSHOT
查看>>
Linux学习7之Shell基础--Bash的变量
查看>>
VirtualBox虚拟机增加CentOS根目录容量 LVM扩容
查看>>
Nginx 和 PHP 的两种部署方式比较
查看>>