jquery - Javascript variable scope not working -


this question has answer here:

i trying parse json. using

$getjson 

to file , save it's content variable

jsonfile 

, passing parsing function, outside getjson function contains null , inside it, contains proper data thought, variable

jsonfile 

is declared globally ( think ). javascript beginner. please explain going on here or point me similar ( coulnd't find myself ).

var atlasjson = "http://127.0.0.1:8000/sprites/sprite.json"; var jsonfile = null;  function setup(){      body = document.getelementbyid('body');     canvas = document.createelement('canvas');      spritemanager = new spritesheetclass();     spritemanager.load(spritesheet);       $.getjson(atlasjson, function(data) {         jsonfile = data;         console.log(jsonfile); // json file content here     });      console.log(jsonfile); // null !!!     debugger;      spritemanager.parseatlasdefinition(jsonfile);      for(var i=0; i<spritemanager.sprites.length ; i++){         console.log(spritemanager.sprites[i]);         }      //canvas = document.getelementbyid('canvas');     ctx = canvas.getcontext('2d');      canvas.setattribute('width', 1024);     canvas.setattribute('height',800);      body.appendchild(canvas); }; 

$.getjson asynchronous, means when call:

$.getjson(atlasjson, function(data) {         jsonfile = data;         console.log(jsonfile); // json file content here     }); 

then

console.log(jsonfile); // jsonfile null... 

it expected behaviour. json available when function(data) called.

what happens function getjson not block code execution. send off request server on network , wait return data. code continue execute on next line of code (console.log in case) , forth until the data remote server recieve. once such data received call function.

what can in function, once returns assign json global variable can access anywhere in code ie.

var jsondata = null; 

then once function(data) called assign variable. way (and once function(data) called will) available javascript code.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -