2016-03-08 29 views
0

我知道在這裏有很多關於如何全局化已在json回調函數中更新的變量範圍的問題。我一直試圖擺脫這些例子好幾天,但我似乎無法解決當我的json回調函數在eg.on右鍵單擊(上下文菜單)時我能如何適應我的代碼。我一直在試圖用這個例子,但都沒有成功嘗試,並使其適應我的代碼:當回調是一個事件函數時,d3中的變量作用域

function myFunc(data) { 
console.log(data); 
} 

d3.json('file.json', function (data) { 
var json = data; 
myFunc(json); 
} 

我在D3的散點圖工作。我的第一個連接只是將兩行表格添加到兩個數組中。每一行代表一個點。當我點擊其中一個點時,將建立與數據庫的連接,並將指向該點的鏈接作爲其他點出現在圖上。這些被添加到baseData數組,並且libraryData保持不變。當我點擊其中一個點時,點將被添加到libraryData數組中。但是,如代碼所示,該函數外部的libraryData實例尚未更新。下面是我的代碼

var libraryData = []; 
var baseData = []; 


d3.json("connection4.php", function(error,dataJson) { 

dataJson.forEach(function(d) { 
    d.YEAR = +d.YEAR; 
    d.counter = +d.counter; 
    libraryData.push(d); 
    baseData.push(d); 
    }) 

var circles = svg.selectAll("circle") 
     .data(libraryData) // libraryData here remains unchanged even after librayData has been updated in the function below! 
     .enter() 
     .append("circle") 
     .attr("class", "dot") 
     .attr("r", 3.5) 
     .attr("cx", function(d) {return x(YearFn(d))}) 
     .attr("cy", function(d) {return y(Num_citationsFn(d))}) 
     .style("fill","blue") 
     .on("click", clickHandler) 

function clickHandler (d, i) { 

    d3.json("connection2.php?paperID="+d.ID, function(error, dataJson) { 

       dataJson.forEach(function(d) { 

        d.YEAR = +d.YEAR; 
        d.counter = +d.counter; 

       baseData.push(d); 

       }) 

var circles = svg.selectAll("circle") 
           .data(baseData) 
           .enter() 
           .append("circle") 
           .attr("class", "dot") 
           .attr("r", 3.5) 
           .attr("cx", function(d) {return x(YearFn(d))}) 
           .attr("cy", function(d) {return y(Num_citationsFn(d))}) 
           .style("fill", "red") 
           .on("contextmenu", rightClickHandler); 
}) 

function rightClickHandler (d, i) { 

    d3.json("connection6.php?paperID="+d.ID, function(error, dataJson) { 

       }) 

      d3.select(this) 
       .style("fill", "blue"); 

     libraryData.push(d); 
     console.log(libraryData);// updated 

    } 
console.log(libraryData)// not updated 

}); 

我是新來D3,我會提前得到任何幫助和反饋謝謝!

回答

1

這不是範圍,這是一個時間問題

function rightClickHandler (d, i) { 

    d3.json("connection6.php?paperID="+d.ID, function(error, dataJson) { 

       }) 

      d3.select(this) 
       .style("fill", "blue"); 

     libraryData.push(d); 
     console.log("I bet I'm second", libraryData);// updated 

    } 
console.log("I bet I'm first", libraryData)// not updated 

}); 

在JSON調用function(error, dataJson)只有一次JSON是從你的PHP函數,它可能需要一段時間恢復執行。同時,你的程序對console.log執行第二次調用,並在json調用中的函數向libraryData添加任何內容之前立即運行。

運行與變化上面CONSOLE.LOG看到

要做到這一點取決於庫數據更新必須內function(error, dataJson)

被稱爲基本上什麼
相關問題