Reputation: 4314
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.
Upvotes: 0
Views: 394
Reputation: 37506
You're modifying what toObj
points to, not what the global points to when you say toObj = data
.
For example, this should work:
toObj.data = data;
That's because you're adding a new attribute. Alternatively, you could something like this:
$.each(data, function(key, value) {
toObj[key] = value;
});
Upvotes: 2