In my code below, I have a function that asynchronously loads all files necessary for an app and when all files are loaded I continue app execution:
function loadDATA(){
var numFILES=6;
var numLoaded=0;
var dfd=$.Deferred();
function fetchJSON(fileName,toObj){
$.ajax({url: fileName, dataType: 'json',
success: function(data){
if(data){
toObj=data;
}
numLoaded++;
if(numLoaded==numFILES){dfd.resolve()};
}
});
}
fetchJSON(TOCfile,TOC);
fetchJSON(MAPfile,MAP);
fetchJSON(CONTENTfile,CONTENT);
fetchJSON(TABLESfile,TABLES);
fetchJSON(CAPTIONSfile,CAPTIONS);
fetchJSON(BOXESfile,BOXES);
return dfd;
}
The objects TOC, MAP, CONTENT, TABLES, CAPTIONS, BOXES are all pre-defined globally to {} at the top of the script.
loaDATA is called like so:
loadDATA().done(function(){
//do stuff with all loaded data here
})
Everything works as expected EXCEPT that the GLOBAL objects are not assigned the new value. INSIDE the success handler, toObj has the value of data, but the GLOBAL object is not modified. Why? Does it have to do with scope?
Thanks for any help with this.
You’re modifying what
toObjpoints to, not what the global points to when you saytoObj = data.For example, this should work:
That’s because you’re adding a new attribute. Alternatively, you could something like this: