Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Setting class property from ajax success

I have a "class"/function called Spotlight. I'm trying to retrieve some information through ajax and assign it to a property of Spotlight. 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 have assigned the object to an array, and it would be difficult to get to it from within Spotlight, so I'm hoping to access everything using 'this.' It appears though that the success function is outside of the class, and I don't know how to make it inside the class.

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

like image 437
Tyler Avatar asked Jan 14 '13 18:01

Tyler


1 Answers

The value of this is dependent on how each function is called. I see 3 ways around this problem:

1. Creating an alias to this

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

2. Using 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 bound function as the callback

this.getAreaSuccess = function (data) {
    this.area = data;
};
this.getArea = function () {
    $.ajax({
        url: base_url +'spotlight/aGetArea',
        type: 'POST',
        success: this.getAreaSuccess.bind(this)
    });
};
like image 56
bfavaretto Avatar answered Sep 18 '22 23:09

bfavaretto