Reputation: 23
I have a class like this :
var MyClass = function(){
this.field = 'field';
}
MyClass.prototype.doSth(data){
//doSth with data and this.field;
}
MyClass.prototype.getData(){
$.ajax({
type: "post",
url: 'myurl',
}).success(this.doSth);
}
but in doSth all 'this' point to the jquery ajax object not MyClass instance.
I added a static filed _self
to point MyClass
self MyClass._self = this;
then change all the this
to MyClass._self
in doSth can fix. But I think this is ugly.
I want to know is there any way to solve my problem with out modify doSth body?
Upvotes: 0
Views: 320
Reputation: 13853
You can pass an object using the context parameter to be used int he callbacks.
$.ajax({
type: "post",
url: 'myurl',
context: this
}).success(function(d){
this.doSth(d);
});
Upvotes: 3
Reputation: 6435
I think you mean:
MyClass.prototype.getData = function(){
var self = this;
$.ajax({
type: "post",
url: 'myurl',
}).success(function(){
self.doSth();
});
};
The definition of "getData" needs to a function as shown here - your version didn't make a lot of sense.
Or you could even use jQuery.proxy (See http://api.jquery.com/jQuery.proxy/ )
MyClass.prototype.getData = function(){
$.ajax({
type: "post",
url: 'myurl',
}).success( $.proxy(this.doSth, this) );
};
$.proxy creates a wrapper function which will call the enclosed function in the context of the given object.
Upvotes: 0