Jquery – How to bind “this” for jQuery callbacks

ajaxjquery

I am trying to set up a callback in jQuery that correctly binds "this" to the calling object. Specifically, here is the code I am working with. I am doing an ajax call in a Object like this:

Object.prototype.doAjaxCall = function(url)
    {
        $.get(url, null, this.handleAjaxResponse );
    }

However, in Object.prototype.doAjaxCall, this does not refer to the correct thing. I have worked with Prototype before and I know you need to bind this when you do the Ajax call, but I can't seem the find the correct way to do that in jQuery. Can someone point me in the right direction?

Best Answer

Use the jQuery ajax context property to bind this. eg:

$.ajax({
    context: this,
    url: url,
    type: 'GET'
}).done( function(data, textStatus, jqXHR) {
    this.handleAjaxResponse();
});