2015-05-04 34 views
0

是否可以更改D3中被视为“链接”的内容?我从服务器接收的JSON被设置为“节点”和“边缘”而不是“节点”和“链接”。下面是一个简单的JSON:在D3中对链接使用不同的命名约定

{ 
"nodes": [ 
{"fixed":true,"data": {"id": "foo","idType":"USERNAME","color":"red"},"selected":false}, 
{"fixed":true,"data": {"id": "bar","idType":"USERNAME","color":"yellow"},"selected": false} 
], 
"edges": [ 
{"classes":null,"data":{"color":"blue","source":"foo","target":"bar","visible":true},"grabbable":false}, 
{"classes":null,"data":{"color":"green","source":"bar","target":"foo","visible":true},"grabbable":false} 
]} 

起初我还以为它是从

var link = svg.selectAll(".link"), 
    node = svg.selectAll(".node"); 

宣布然而当我改变.link.edge我的代码中断。

// sets the source and target to use id instead of index 
var edges = []; 
root.edges.forEach(function(e) { 
    var sourceNode = root.nodes.filter(function(n) { 
       return n.data.id === e.data.source; 
      })[0], 
      targetNode = root.nodes.filter(function(n) { 
       return n.data.id === e.data.target; 
      })[0]; 

    // push the attributes in the JSON to the edges. 
    edges.push({ 
     source: sourceNode, 
     target: targetNode, 
     label: e.data['label'], 
     color: e.data['color'] 
    }); 
}); 

force 
     .nodes(root.nodes) 
     .links(edges) 
     .start(); 

link = link 
     .data(edges) 
     .enter().append("line") 
     .attr("class", "link") 
     .style("stroke-width", 1.5); 

node = node 
     .data(root.nodes) 
     .enter().append("g") 
     .attr("class", "node"); 
+0

我认为它不重要什么d3称它。你如何初始化你的图表? – Halcyon

+0

我会用代码更新我的问题。这有点长。 – Joey

回答

0

太平的约D3不关心你叫什么links评论使我意识到,我的代码是不是从图形的实际初始化打破。它正在破坏我利用id作为source/target而不是默认index的方式。

更改root.links.forEach...root.edges.forEach...修复了这个问题。