return a global variable in d3.js

时间:2015-09-01 21:15:36

标签: javascript d3.js

I need to get the result of this algorithm called cartogram. This result is asynchronous, that is why it does not work with define a global variable. I need to get the json object that generates this: "features.features".

d3.json ("mapaoriginal.topojson" function (topology) {
                            var = cartogram features (topology, topology.objects.collection.geometries);
                            d3.select ("SVG")
                                .attr ("width", 1000)
                                .attr ("height", 500)
                              .selectAll ("path")
                                .data (features.features)
                                .enter ()
                              .append ("path")
                                .attr ("d" cartogram.path);
        })

My idea is to have something.

result = features.features;

and then use "result" outside the function. if I define a global variable, it always appears undefined. how I can get out of the function I need?

1 个答案:

答案 0 :(得分:0)

Under the assumption that what is asynchronous is d3.json and not cartogram. If cartogram is asynchronous you have to check the documentation / code to identify if there is a way to provide a callback function for when the operation completes (otherwise you have to use a global event handler if that is possible of use setInterval for periodically checking if the operation has completed - both are not recommended unless there is no other alternative)

then use "result" outside the function.

result is initialized only once the asynchronous operation completes. So if you want to get the value, you have to wait for the callback (function) to start executing.

if I define a global variable, it always appears undefined. how I can get out of the function I need?

You can define a separate function to do what you want to do with features.features and call it in your callback. This will help keep your lines of code outside of the callback function.

Something like

d3.json ("mapaoriginal.topojson" function (topology) {
      // do current stuff
      // myFunction(features.features) that uses features.features
})

function myFunction(f) {
     // do stuff with f (features.features)
}

There is an alternative where you use a global even handler to listen for the JSON response or you set up a setInterval to check for the global variable value periodically - however this is almost always results in hard to maintain code and is NOT recommended.