【发布时间】:2014-12-08 16:32:10
【问题描述】:
基本上,我想从集合中随机呈现一个标题列表,然后在用户触发“loadMore”标题事件时使用不同的标题集重新呈现该列表。
我有一个 StoryList 视图,它为我的集合中的每个模型附加了一个新的 StoryListItem 视图。我还使用下划线方法 sample() 来随机化和限制模型的数量,从而限制渲染的 StoryListItem 视图的数量。最后,我有一个委托给这个视图的事件,称为“loadMore”。我希望 loadMore 事件使用与原始集合不同的样本重新渲染视图。
目前,loadMore 事件基本上重构了原始集合(采样模型包含属性“models”,其中包含我们最初采样的所有模型),然后重新渲染视图。结果是在原始视图元素之后附加了第二个视图元素。我只知道我的方法不对,我希望有人可以让我走上正确的道路。
sbk.StoryListView = Backbone.View.extend({
tagName: 'ul',
id: 'story-list',
initialize: function () {
this.collection.on('reset', this.render, this);
console.log('initialize');
},
template: Handlebars.compile($('#story-list-template').html()),
render: function () {
var newCollection = _.sample(this.collection.models, 4);
_.each(newCollection, function (storyItem) {
$(this.el).append(new sbk.StoryListItemView({model: storyItem}).render().el);
}, this);
$(this.el).append(this.template());
return this;
},
events: {
'click #load-more' : 'loadMore'
},
loadMore: function(){
this.collection = new Backbone.Collection(this.collection.models);
this.render();
}
});
【问题讨论】: