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
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
Share Improve this question asked Jul 3, 2011 at 13:30 Ermes Enea ColellaErmes Enea Colella 1511 silver badge10 bronze badges 1-
notwithstanding your scope problem, you can't overwrite
this
– Alnitak Commented Jul 3, 2011 at 13:43
3 Answers
Reset to default 5The 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
}
});
}
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.
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;
...
}
});
}