Reputation: 2342
//this is a class
function SpriteSheetClass()
{
this.sprite="local";
$.getJSON(url, this.onLoaded);
}
SpriteSheetClass.prototype.onLoaded= function(json)
{
console.log(this.sprite); //returns undefined!
//I am out of SpriteSheetClass scope! how do I store the json???
}
var a=new SpriteSheetClass()
When the getJSON callback is executed, the scope is not in the class. There is no way to bind the returned json with my class instance (a)
Keep in mind I want to keep the calls async, and I need to create many instances of SpriteSheetClass This is not a timing question, it is a scope question.
thanks
Upvotes: 1
Views: 1090
Reputation: 207521
With modern day browsers you can use function.bind(thisArg) to keep the proper scope.
function SpriteSheetClass() {
this.sprite="local";
$.getJSON(url, this.onLoaded.bind(this));
}
Upvotes: 1
Reputation: 318232
When the callback function is called, this
will not be the object, but the $.getJSON
function.
You can bind the value of this
to the callback, so it will be the object instead
$.getJSON(url, this.onLoaded.bind(this));
Upvotes: 1
Reputation: 36438
A local wrapper function will do the job:
function SpriteSheetClass()
{
this.sprite="local";
var that = this;
var callback = function(data) {
that.onLoaded(data);
};
$.getJSON(url, callback);
}
Upvotes: 0