2014-01-26 30 views
1

我是D3新手,看起來很酷。我想我會嘗試使用方向力佈局來構建一些東西。通過D3中的額外數據循環定向力佈局

我所試圖做的

我通過創建一個JSON對象for循環加我的所有項目準備在force.start使用()。這工作正常。但是我想通過不同的json源添加更多的數據。要做到這一點,我有第一個循環內的另一個循環,以在第一個循環中添加更多基於數據的數據(請參閱代碼)。

我有多遠了

我的控制檯登錄,我可以看到,項目被壓到我的JSON對象但他們沒有得到force.nodes正確的屬性();見:

group: 2 
name: "Alt-J" 
px: NaN 
py: NaN 
x: NaN 
y: NaN 

這是爲什麼? 對我來說,好像圖是在循環完成之前構建的,並且項目已正確添加。

繼承人我的代碼:

// Get the users top played artists 
d3.json("http://ws.audioscrobbler.com/2.0/?method=user.gettopartists.gettopartists&user="+ username +"&api_key=be4ff3242bdb1d653517df99df39cfe2&format=json", function(error, graph) { 
    // Loops through them and push them in nodes.names[] 
    for (var i = 0; i < graph.topartists.artist.length; i++) { 
    var item = graph.topartists.artist[i]; 
    // Then get for each top artist their respect related artists 
    d3.json("http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&artist="+ item.name +"&api_key=be4ff3242bdb1d653517df99df39cfe2&format=json", function(error, related) { 
     // Do this just for 5 item to reduce load 
     for (var i2 = 0; i2 < 5; i2++) { 
      var relatedItem = related.similarartists.artist[i2]; 
      console.log(i2); 
      // Add those to our json object like with top artists 
      nodes.names.push({ 
      "name" : relatedItem.name, 
      "group" : 2 
      }); 
      nodes.links.push({ 
      "source" : i + i2 , 
      "target" : 0 
      }); 
     } 
     console.log(nodes.names); 
    }); 

    nodes.names.push({ 
     "name" : item.name, 
     "group" : 1 
    }); 
    nodes.links.push({ 
     "source" : i, 
     "target" : 0 
    }); 
    } 
    force 
     .nodes(nodes.names) 
     .links(nodes.links) 
     .distance(20) 
     .start(); 

回答

2

這樣做的原因是,d3.json是異步的。也就是說,回調不立即執行,但是當獲得JSON的調用返回時。這意味着在嵌套的d3.json調用返回並添加數據之前,將運行用於初始化和啓動強制佈局的代碼塊。

這不是一個問題 - 你當然可以在給force.nodes()force.links()的陣列中添加新的項目。問題是這些新項目的位置沒有初始化,只發生在force.start()。所以在添加新節點/鏈接之後,您需要再次啓動強制佈局。

您應該能夠在代碼中修復此問題,方法是在每個嵌套的回調結束時聲明force,並調用force.start()

+0

謝謝拉斯。我會盡快調整我的代碼。我看到你的答案在D3問題上出現很多。你知道任何好的在線資源/教程嗎?乾杯 –

+0

在D3網站上鍊接的教程通常是一個很好的開始和覆蓋很多材料的地方。 –