2013-12-12 71 views
1

我有一個樹形佈局。如圖中JSBin http://jsbin.com/AbOmAZE/11/更新可視化背後的數據

在與一個節點相關聯的文字點擊事件,我想可視化背後的數據進行更新(我需要更新樹佈局背後的數據,因爲它是用作接口)。我已經實現了重畫和click事件,但是我不知道如何僅僅通過知道從click函數返回的當前選擇來更新數據。

node.append("text") 
    .text(function(d){ return d.name; }) 
    .on('click', function(d){ 
    var result = prompt('Change the name of the node',d.name) 
    if(!result) { 
     d.name = result; // !!! This is where the problem is. 
    } 
    console.log(d) 
    draw(); //This redraws the graph 
    }) 

請參考上面發佈的JSBin。

回答

3

與D3玩弄2個月後,我終於明白,正是我感到困惑:

我一直在尋找一種方式,它一直使用D3更新後提取數據。

這是相當簡單,包括兩個主要步驟:

  1. 獲取數據陣列

    對於這個步驟,你只需要選擇您最初綁定數據使用的元素。 data() - 在這種情況下,它是.nodes元素

    var node = d3.select('svg').select('.nodes')

    然後,您需要使用.data()函數獲取數據。這將爲每個可用節點返回一個數組。既然你要爲整個樹中的數據,通過使第一項的數據與[0]

    var data = node.data()[0]

  2. 濾波器陣列中的數據

    現在選擇的節點根我們有數據,但是運行d3.tree(數據)已經添加了一些屬性,如'x'和'y'值。爲了得到它類似於您最初放在你的人需要一個遞歸濾波功能的陣列:

    function filter(data) { 
        for(var i in data){ 
        if(["depth","x","x0","y","y0","parent","size"].indexOf(i) != -1){ 
         delete data[i]; 
        } else if (i === "children") { 
        for (var j in data.children) { 
         data.children[j] = filter(data.children[j]) 
         } 
        } 
        } 
    return data; 
    } 
    

現在你有一個更新的信息數組由D3作爲修飾,沒有任何額外的屬性d3已經加入了這個過程。現在可以將該數組保存回數據庫。

也希望看到一個完全工作的例子,check out this jsbin

1

的問題是,你試圖redraw樹視圖。 d3enterupdateexit選擇照顧變化的基礎數據。我修改了jsbin here,並相應地更新了節點。

node.append("text") 
    .text(function(d){ return d.name; }) 
    .on('click', function(d){ 
    console.log(d); 
    var result = prompt('Change the name of the node',d.name); 
    if(result) { 
     d.name = result; 
     var node = canvas.selectAll('.node').data(nodes); 
     node.select('text') 
     .text(function(d){ return d.name; }); 
    } 
    }); 
+0

非常感謝您的幫助。視圖如何通過底層數據進行更新是很棒的。 然而,我仍然面臨的問題是將綁定的數據放回到我的數據數組中。我需要這個,所以我可以將更改寫回到我的數據庫。 – Paul