【发布时间】:2014-03-19 20:20:02
【问题描述】:
问题:如果在获取集合时在成功回调之外调用渲染方法,我的集合无法呈现到页面。
我有一个基本的骨干集合,在它从我的服务器获取一些 json 后,我试图将它呈现给我的应用程序。在学习了一堆教程之后,我希望它会像这样工作:
var restaurants = new RestaurantsCollection();
var restaurantsView = new RestaurantsView({collection: restaurants});
restaurants.fetch():
$(curate.targets.restaurantApp).append(restaurantsView.render().el);
集合成功获取 json,但从未附加到页面。
或者,如果我附加在fetch() 的成功回调中,它会附加到页面罚款。像这样:
var restaurants = new RestaurantsCollection();
var restaurantsView = new RestaurantsView({collection: restaurants});
restaurants.fetch({
success: function(collection){
console.log(collection);
$(curate.targets.restaurantApp).append(restaurantsView.render().$el);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
console.log(jqXHR);
}
});
餐厅视图:
var RestaurantsView = Backbone.View.extend({
el: $(curate.targets.restaurantList),
initialize: function(){
this.collection.fetch();
this.listenTo(this.collection, 'reset', this.render, this);
},
render: function(){
this.addAll();
return this;
},
addAll: function(){
this.collection.forEach(this.addOne, this);
},
addOne: function(RestaurantModel){
var restaurantView = new RestaurantModelView({model: RestaurantModel});
this.$el.append(restaurantView.render().el);
}
});
是否需要在fetch()的成功回调中追加渲染和追加视图或者有没有更好的方法?
【问题讨论】:
-
您需要使用回调,因为 fetch 是异步的。或者,您可以将集合的“添加”事件绑定到您的视图
-
@Gohn67 我知道 fetch 是异步的,但必须有一种更简洁的方法来创建我的集合并呈现我的视图,对吗?还是这样
-
您实际上在哪里“渲染” html?另外,我认为“同步”是更好听的事件。仅当您调用“reset()”时才会触发“reset”事件 - 我在您的代码中也没有看到。我在看1.0.0版本的源代码。
-
@anAgent 你的权利,将事件更改为
sync让我在获取时呈现集合,就像我想要做的那样。休息只适用于this.collection.fetch({reset: true});。如果你用这个更新你的答案,我会接受它。 -
太好了,很高兴听到!我已经更新了我的答案。