2

I create the following class :

APP.core.View = function () {
    var self = this;

    $.ajax ( { url: 'test.html' } ).done ( self.build );

    return self;
};


APP.core.View.prototype.build = function ( source ) {
    var self = this;

    // this refers to the AJAX callback.

    return self;
};

As you can see in the build method, the reference to this (the one belonging to APP.core.View) has been lost. How can I get it back ? I know I could pass a ref to this in the AJAX callback like this :

$.ajax ( { url: 'test.html' } ).done ( function ( source ) {
    self.build ( source, self );
} );

But I don't really like it as I feel like a method should never loose the ref to its object.

Any idea/suggestion ? :)

2 Answers 2

2

You can use $.proxy() to create a cross platform solution

APP.core.View = function () {
    $.ajax({
        url: 'test.html'
    }).done($.proxy(this.build, this));
    return this;
};

For modern browsers, you can use .bind()

APP.core.View = function () {
    $.ajax({
        url: 'test.html'
    }).done(this.build.bind(this));
    return this;
};
Sign up to request clarification or add additional context in comments.

Comments

0

I just found another answer in the jQuery AJAX doc. The jQuery.ajax function provides a context argument which lets you specifies the callbacks context. Example :

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() {
  $( this ).addClass( "done" );
});

Source : http://api.jquery.com/jQuery.ajax/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.