不知道你为什么不使用模型。回答你的问题,有不同的解决方案,第一个:
使用事件:
app.SomeView = Backbone.View.extend({
render: function() {
var that = this;
$.getJSON(someURL, function(result) {
that.property = result.something;
that.trigger('DataLoaded', that);
});
return this;
}
});
var view = new app.SomeView();
view.on('DataLoaded', function(theView){
console.log( theView );
});
第二个,你需要添加一个回调并传递它:
app.SomeView = Backbone.View.extend({
render: function(callback) {
var that = this;
$.getJSON(someURL, function(result) {
that.property = result.something;
callback(that);
});
return this;
}
});
var view = new app.SomeView();
view.render( function(theView){
console.log( theView );
});
我的答案是为解决您创建的问题而编写的。但是对于长期的改进,你知道 Models 有一个 fetch 方法,它基本上从服务器加载 JSON 并将其关联到 Model 吗?
http://backbonejs.org/#Model-fetch
这就是我将如何加载 JSON:
app.SomeModel = Backbone.Model.extend({
urlRoot : someURL
});
app.SomeView = Backbone.View.extend({
initialize : function(){
this.model.on('change', this.render);
},
render: function() {
console.log( this.model.toJSON() );
return this;
}
});
var view = new app.SomeView(new app.SomeModel());
view.model.fetch();