Ermes Enea Colella
Ermes Enea Colella

Reputation: 151

Jquery ajax: pass the scope to set it

I have this class with this ajax call:

Person = function () {

    this.__type = "PersonDto:#Empower.Service.Common.Dto";
    this.Name = undefined;
    this.Surname = undefined;

    this.GetById = function (id) {
        return $.ajax({
            type: "POST",
            url: "/Services/PersonService.svc/GetPersonById",
            data: JSON.stringify(id),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                ...
                this = data;
                ...
            }
        });
    }
};

In success of ajax call i want to set the current instance of person, but "this" is not scope correct for setting. There is a more elegant way than using a global variable?

Thank you in advance for your help, and I apologize for my bad English

Upvotes: 3

Views: 2902

Answers (3)

user113716
user113716

Reputation: 322472

The jQuery.ajax()[docs] method gives you a context property where you can set the value of this in the callbacks.

Just do:

context: this,

...in your call, as in:

this.GetById = function (id) {
    return $.ajax({
        type: "POST",
        context: this,  // <---- context property to set "this" in the callbacks
        url: "/Services/PersonService.svc/GetPersonById",
        data: JSON.stringify(id),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {

             // in here, "this" will be the same as in your "getById" method

        }
    });
}

Upvotes: 5

Tx3
Tx3

Reputation: 6916

Sure, you can put this to a variable and then use that variable in your callback

var self = this;

this.GetById = function (id) {
    return $.ajax({
        type: "POST",
        url: "/Services/PersonService.svc/GetPersonById",
        data: JSON.stringify(id),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            ...
            self = data;
            ...
        }
    });
}

Upvotes: 0

Alnitak
Alnitak

Reputation: 339786

You don't need a global.

Just put:

 var self = this;

immediately before the return $.ajax(...) line, and then use self to reference the current instance inside the AJAX callback function.

This variable will only be in scope within the GetById() funciton.

Upvotes: 1

Related Questions