I have this code:
var my = {};
(function () {
var self = this;
this.sampleData = { };
this.loadData = function() {
$.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?',
{tags: "cat", tagmode: "any", format: "json"},
function(data){
self.sampleData = data;
}
);
};
}).apply(my);
my.loadData();
console.log(my.sampleData); // {}
The problem is my.sampleData not have anything.
Try this sample here: http://jsfiddle.net/r57ML/
The reason is that the
getJSONcall is asynchronous, so you’re looking for the data before it’s been returned. Instead, put your code using the data inside the callback, either directly or indirectly.For instance, you can have your
loadDatacall accept a callback:Side note: Since your
myobject is a singleton, you can simplify that code a fair bit, no need forapply,this, orself, since your anonymous function is a closure over the context in whichmyis defined:Of course, if you’re using a constructor function or something instead (you weren’t in your quoted code, but…), then of course you might need the more complex structure.