2

我创建了以下类:

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

正如您在build方法中看到的,对this(属于 APP.core.View 的那个)的引用已经丢失。我怎样才能把它拿回来?this我知道我可以像这样在 AJAX 回调中传递一个 ref :

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

但我真的不喜欢它,因为我觉得一个方法永远不应该将 ref 松散到它的对象上。

有什么想法/建议吗?:)

4

2 回答 2

2

您可以使用$.proxy()创建跨平台解决方案

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

对于现代浏览器,您可以使用.bind()

APP.core.View = function () {
    $.ajax({
        url: 'test.html'
    }).done(this.build.bind(this));
    return this;
};
于 2013-10-30T13:21:01.187 回答
0

我刚刚在 jQuery AJAX 文档中找到了另一个答案。jQuery.ajax 函数提供了一个context参数,可让您指定回调上下文。例子 :

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

来源:http ://api.jquery.com/jQuery.ajax/

于 2013-10-31T10:04:43.647 回答