javascript - 数据绑定(bind)中的 D3 键函数如何工作

标签 javascript d3.js

全部:

[更新]

Finally figure out how D3 key function works conceptually: when using .data(newdata, key_function), this function will extract old bined data from element and put it into this key function get a key, and do same thing with the newdata, and compare them, if same, replace the old data with new data. important thing(to me) here is: the key( for old data and new data) is always generated by current key_function, so once we change key function, and if we still want to bind data to original element, we need find a way to make sure the key can be consistent.

The official explain is here(according to Cool Blue): https://github.com/mbostock/d3/wiki/Selections#data

我是 D3 数据绑定(bind)的新手,阅读后http://bost.ocks.org/mike/selection/ ,还有一个问题是D3键的作用是怎样的:

我想知道每一轮数据更新是独立的还是与上一轮数据绑定(bind)指定的key有关?(key如何存储:是否作为属性存储在元素中?如果没有指定key函数会被删除吗稍后)

喜欢

第一轮数据绑定(bind):

var letters = [
  {name: "A", frequency: .08167},
  {name: "B", frequency: .01492},
  {name: "C", frequency: .02780},
  {name: "D", frequency: .04253},
  {name: "E", frequency: .12702}
];

function name(d) {
  return d.name;
};

var color = d3.scale.category20();

var divs = d3.selectAll("div")
             .data(letters, name);
divs.enter()
    .append("div")
    .style("width", 50)
    .style("height", function(d, i){
        return d.frequency*500+"px";
    })
    .style("background-color", function(d, i){
        return color(i);
    });

然后对数据进行排序并再次绑定(bind):

    letters.sort(function(a, b){
        return a.frequency - b.frequency;
    });

[1] 与关键功能绑定(bind):

    divs.data(letters, name)
        .transition()
        .style("background-color", function(d, i){
            return color(i);
        })
        .style("height", function(d, i){
            return d.frequency*3000+"px";
        });

或 [2] 无按键功能绑定(bind):

    divs.data(letters)
        .transition()
        .style("background-color", function(d, i){
            return color(i);
        })
        .style("height", function(d, i){
            return d.frequency*3000+"px";
        });

谁能给我解释一下这两种不同的数据绑定(bind)发生了什么?我主要的困惑是,如果我在数据更新时没有指定键函数,是否会删除绑定(bind)到该元素的旧键,然后根据索引直到指定另一个键函数?

最佳答案

key 函数不会改变底层数据,它只是告诉 D3 如何提取标识属性——每个数据(在传递给 .data() 并绑定(bind)到 DOM 的数据中) elements) 将被传递给 key 函数,返回值将用于匹配元素(即那些为 DOM 元素和数据返回相同值的元素)。

如果您在更新时更改关键功能,则计算的选择将相应更改。仅此而已。

关于javascript - 数据绑定(bind)中的 D3 键函数如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30174251/

相关文章:

javascript - D3.js 或 EXT js 用于数据可视化,为什么?

javascript - 分形螺旋图 : possible rounding errors in javascript

javascript - 使用 Apps 脚本生成公钥/私钥 RSA

javascript - JS - 检查元素呈现的不透明度值

c# - 如何从代码隐藏中获取 javascript 中设置的值?

javascript - 如何不断更新d3图中x轴的范围?

javascript - 根据月份突出显示行

javascript - 使用 PhantomJS 将多个页面渲染为 pdf 文件

javascript - d3js v5 标准化堆积条形图

d3.js - 如何自定义 D3 折线图中的色阶?