D3 JS - 强制图 - 删除节点后不重新启动布局

时间:2014-09-11 13:45:13

标签: javascript svg d3.js force-layout

更新: 删除节点后,图表现在可以正常运行。 但是,当我有条件地删除非顺序节点(例如4,5,10)时,图形不会显示正确的节点。

请查看下面更新的点击处理程序(大量调试)。 我试图用" d.source"删除所有节点。 value ==" news24",这些都是大蓝圈。 虽然在"删除"之后阵列是正确的,但是正在显示不正确的节点。 我怀疑它与node.exit()有关,但我不确定。

完整更新的代码:http://www.darkness.co.za/code/graph_test_2.zip

$('#btnRemove').click(function(e) {
// These are the large blue circles  
var sourceToHide = "news24";

// DEBUG - Before Removal
for (i=0; i < nodes.length; i++) {
  console.log("node_object[" + i + "].source = " + nodes[i].source);
  console.log("-----------------------------------");
}

// Hold indices of items to remove  
var itemsToRemove = [];

// Find items with the source to remove
for (i=0; i < nodes.length; i++) {
    var nodeSource = nodes[i].source;

    console.log("Node source = " + nodeSource + " sourceToHide = " + sourceToHide);         

    if (nodeSource == sourceToHide) {
        itemsToRemove.push(i);
    }
}

// Reverse removal array - makes splice work as expected
itemsToRemove.reverse();

// Remove items
for (i=0; i < itemsToRemove.length; i++) {
    nodes.splice(itemsToRemove[i], 1);
}

// DEBUG - After Removal
for (i=0; i < nodes.length; i++) {
    console.log("node_object[" + i + "].source = " + nodes[i].source);
    console.log("-----------------------------------");
}   

// Rebind the nodes to the array
node = svg.selectAll("circle")
.data(nodes)

// Remove the exit'ed node
node.exit().remove();

// Tell the layout that this is the new set of nodes
// so that it doesn't include the old one in the computation
force
.nodes(nodes)

// That's it. No need to restart the force layout

});

我已经搜索了很多,并且单独尝试了很多示例,但无法针对我的特定设置和数据解决此问题。

代码:
道歉,我在JSFiddle(外部文件等)上设置它时遇到了问题,所以你可以在这里获得完整的代码: http://darkness.co.za/code/graph_test.zip

我想要达到的目标:
(对于此测试)我想删除单个节点,然后重绘/重新启动图表

我尝试了什么:
我试图从节点数组中删除最后一个元素,然后重绘图形(圆圈和线条),然后调用force.start()

问题:
节点确实会根据需要消失,但整个图表停止响应。

如何正确删除节点,然后使用正常的拖动行为成功重新启动图表?

注意:我在&#34; drawGraph()&#34;函数调用&#34; force.start()&#34;

由于

1 个答案:

答案 0 :(得分:2)

在这种情况下,您无需“重新启动”图表。您所要做的就是从DOM中删除节点并告诉强制布局有一组新的节点(与MINUS删除的节点相同)。所以,在按钮的点击处理程序中:

// Button Listeners
$('#btnRemove').click(function(e) {
  // Remove the node from the array
  nodes.splice((nodes.length - 1), 1);

  // Rebind the nodes to the array
  node = svg.selectAll(".node")
    .data(nodes)

  // Remove the exit'ed node
  node.exit().remove();

  // Tell the layout that this is the new set of nodes
  // so that it doesn't include the old one in the computation
  force
    .nodes(nodes)

  // That's it. No need to restart the force layout
});

这并不涉及删除节点的链接行,但您可以按照相同的方法来执行此操作。