json - variable scope in d3 javascript -
i want info in global variable using next code:
var data; d3.json ( "file.json" , function(json) { info = json; console.log(data); //defined }); console.log(data); //undefined
but problem have info variable defined in d3.json function out undefined. how can solve issue?
thanks
because d3 requests (like d3.json
) asynchronous, it's best practice wrap of code dependent on external request within request callback, ensuring code has access info before executing. from d3 docs: "when loading info asynchronously, code depends on loaded info should exist within callback function."
so 1 alternative set of code within callback function. if you'd separate code parts, can pass response request separate function, this:
function myfunc(data) { console.log(data); } d3.json('file.json', function (data) { var json = data; myfunc(json); }
javascript json d3.js global-variables
No comments:
Post a Comment