首页 > 解决方案 > 创建路径时丢失数据绑定

问题描述

完全承认我只进入 D3 几周,但我已经在这里坐了几个小时,现在调试无济于事。

注意console.log(d)隐藏在匿名函数中的两个语句。'dummy' 属性上的那个返回值,d属性中的那个不返回值。

这两者有什么不同?

var myEdges = [
    {
        in: "934e3e11-3f9b-11e9-b2b9-c54f58764873",
        out: "936807a1-3f9b-11e9-b2b9-c54f58764873"
    },
]

svg.selectAll('path:not([elementType=temp-path])').data(myEdges)
    .enter().append('path')
        .attr("fill", "none")
        .attr("stroke", "blue")
        .style("stroke-width", "2px")
        .attr('dummy', function(d) { console.log(d); return d;})
        .attr('d', d3.linkVertical()
                                .x(function(d) { console.log(d); return d.in; })
                                .y(function(d) { return d.out; }));

标签: javascriptd3.js

解决方案


问题不在于d没有传递 datum ( ) 属性:它是。这里的问题只是链接生成器所期望的数据结构。

如果您查看API,您会看到链接生成器默认情况下需要这样的数据结构:

{
  source: foo,
  target: baz
}

顺便说一句,您可以使用link.source()和更改这些属性link.target()

所以,如果我们改变你的数据结构,控制台就会工作:

var svg = d3.select("svg");

var myEdges = [{
  source: { in: "934e3e11-3f9b-11e9-b2b9-c54f58764873",
    out: "936807a1-3f9b-11e9-b2b9-c54f58764873"
  },
  target: { in: "934e3e11-3f9b-11e9-b2b9-c54f58764873",
    out: "936807a1-3f9b-11e9-b2b9-c54f58764873"
  }
}]

svg.selectAll('path:not([elementType=temp-path])').data(myEdges)
  .enter().append('path')
  .attr("fill", "none")
  .attr("stroke", "blue")
  .style("stroke-width", "2px")
  .attr('dummy', function(d) {
    console.log("dummy here: " + d);
    return d;
  })
  .attr('d', d3.linkVertical()
    .x(function(d) {
      console.log(d);
      return d.in;
    })
    .y(function(d) {
      return d.out;
    }));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>

最后,这些其他答案可能会帮助您了解链接生成器所需的数据结构:https ://stackoverflow.com/a/44760465/5768908和https://stackoverflow.com/a/51424331/5768908


推荐阅读