2014-09-11 118 views
2

更新: 刪除節點後,圖現在正確運行。 但是,當我有條件地刪除非連續節點(例如4,5,10)時,該圖不會顯示正確的節點。D3 JS - 強制圖 - 刪除節點後不重新啓動佈局節點

請看下面更新的點擊處理程序(大量的調試)。 我試圖刪除所有節點與「d.source」值==「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()

問題:
節點會根據需要消失,但整個圖形停止響應。

如何正確刪除節點,然後用正常的拖動行爲成功重新啓動圖形?

注:我在結束「drawGraph()」函數調用「force.start()」

感謝

回答

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 
}); 

這並沒有解決去除節點的鏈接線的,但你可以按照同樣的方法來做到這一點。

+0

謝謝meetamit!這消除了圖表被移除後「斷開」的情況。當我嘗試刪除多個具有條件的非順序節點時,我遇到新問題。如果我無法弄清楚,我將不得不發佈一個新問題。再次感謝 ! – LavenPillay 2014-09-12 08:20:32