Javascript: setting class property from ajax success

I have a "class" / function called Spotlight. I am trying to get some information through ajax and assign it to the Spotlight property. Here is my Spotlight class:

function Spotlight (mId,mName) { this.area = new Array(); /** * Get all area information */ this.getArea = function () { $.ajax({ url: base_url +'spotlight/aGetArea', type: 'POST', success: function (data) { this.area = data; } }); } } 

I assigned an object to an array, and it would be hard to get to it from within Spotlight, so I hope to access everything using "this." The success function seems to be outside the class, and I don't know how to make it inside the class.

Is there a way to get the data in a class property using this.area rather than Spotlight.area?

+6
source share
3 answers

The meaning of this depends on how each function is called. I see 3 ways to solve this problem:

1. Create an alias for this

 var that = this; this.getArea = function () { $.ajax({ url: base_url +'spotlight/aGetArea', type: 'POST', success: function (data) { that.area = data; } }); }; 

2. Using the jQuery .ajax context option

 this.getArea = function () { $.ajax({ url: base_url +'spotlight/aGetArea', type: 'POST', context : this, success: function (data) { this.area = data; } }); }; 

3. Using a related function as a callback

 this.getAreaSuccess = function (data) { this.area = data; }; this.getArea = function () { $.ajax({ url: base_url +'spotlight/aGetArea', type: 'POST', success: this.getAreaSuccess.bind(this) }); }; 
+11
source

Good Spotlight.area will not work. You just need to save the external this :

 this.area = []; var theSpotlight = this; 

and then in the callback:

  theSpotlight.area = data; 
+4
source

Inside the success function, this corresponds to the scope of the success function.

 function Spotlight (mId,mName) { this.area = []; var scope = this; /** * Get all area information */ this.getArea = function () { $.ajax({ url: base_url +'spotlight/aGetArea', type: 'POST', success: function (data) { scope.area = data; } }); } } 
+1
source

All Articles