简体   繁体   English

d3-对象稳定性,关键功能和(更新,输入,退出)

[英]d3 - object constancy, key functions and (update, enter, exit)

The following jsfiddle works as expected. 以下jsfiddle可以正常工作。

However when I add a key function to the data binding it breaks. 但是,当我向数据绑定中添加键功能时,它会中断。

 // Use source_target as a key to uniquely identify each link.
 var link = svg.selectAll(".link")
     .data(graph.links, function(d){ return d.source + "_" + d.target; });

After reading the ObjectConstancy tutorial I understood that you could assign a custom key to each element instead of relying on its index for (update, enter, exit). 阅读了ObjectConstancy教程后,我了解到您可以为每个元素分配一个自定义键,而不是依靠其索引来进行(更新,输入,退出)。

Is this not the case? 不是吗? What am I doing wrong? 我究竟做错了什么?

The problem is what d.source and d.target evaluate to as strings -- [object Object] . 问题是d.sourced.target评估为字符串- [object Object] Remember that the force layout replaces the indices you specify in your data with the corresponding node objects when you run it. 请记住,强制布局在运行时会将您在数据中指定的索引替换为相应的节点对象。 You are not seeing all the links you are expecting because of this -- the key function returns the same values for different links, hence they are only added once. 因此,您没有看到期望的所有链接-键函数为不同的链接返回相同的值,因此它们只会被添加一次。

To fix, use eg the name of the nodes: 要修复,请使用例如节点名称:

var link = svg.selectAll(".link")
  .data(graph.links, function(d){ return d.source.name + "_" + d.target.name; });

Complete demo here . 在此处完成演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM