Вопрос

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 ? :)

Это было полезно?

Решение

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;
};

Другие советы

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/

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top