6

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?

2 Answers 2

2

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

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

A more robust, native bind function should be part of ECMAScript 3.1. In the meantime...

Object.prototype.doAjaxCall = function(url) {
    var bind = function(context, method) {
        return function() {
            return method.apply(context, arguments);
        };
    };

    $.get(url, null, bind(this, this.handleAjaxResponse));
};

Not the answer you're looking for? Browse other questions tagged or ask your own question.