user1071710
user1071710

Reputation: 23

How can I use keyword 'this' in jQuery ajax success handle

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

Answers (2)

Andrew
Andrew

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

N3dst4
N3dst4

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

Related Questions