2013-10-30 46 views
2

我创建了以下类:jQuery的回调和原型继承

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)已丢失。我怎样才能找回来?我知道我可以在AJAX回调像这样的裁判传给this

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

但我真的不喜欢它,因为我觉得自己像一个方法应该永远不会失去裁判给它的对象。

任何想法/建议? :)

回答

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

我刚刚发现了jQuery AJAX文档另一个答案。 jQuery.ajax函数提供了一个context参数,它允许您指定回调上下文。例如:

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

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