user3561494
user3561494

Reputation: 2342

using getJSON in a class (scoping issue)

//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

Answers (3)

epascarello
epascarello

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

adeneo
adeneo

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));

FIDDLE

Upvotes: 1

Paul Roub
Paul Roub

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

Related Questions