当回调是事件函数时,d3中的变量范围

时间:2016-03-08 15:58:01

标签: javascript json d3.js

我知道这里有很多关于如何全局化json回调函数内已更新的变量范围的问题。而且我一直试图解决这些例子已经好几天但是我似乎无法解决当我的json回调是关于事件时如何将其调整到我的代码中,例如右键单击(上下文菜单)。我一直试图使用这个例子但是没有成功地尝试将它改编为我的代码:

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 个答案:

答案 0 :(得分:1)

这不是范围,而是时间问题

function(error, dataJson)

json调用中的function(error, dataJson)仅在从php函数返回json时执行,这可能需要一段时间。同时,你的程序执行第二次调用console.log立即运行,并且在json调用中的函数向libraryData添加任何内容之前。

使用对console.log的更改运行上面的内容以查看

基本上你要做的任何事情取决于要更新的​​库数据必须在 <address> <ul> <li><a href="http://website.asd" hreflang="en" target="_blank">Website</a></li> <li><a href="mailto:somebody.someone@host.asd" hreflang="en" target="_blank">Contact us</a></li> </ul </address>

内调用