Backbone的优点之一是它不会强制您使用预定义的模式。在您的案例中,您可以按天对模型进行分组,为每个组生成HTML,然后将结果推送到DOM。
为了方便起见,假设您的模型和集合是这样定义的:
var M = Backbone.Model.extend({
day: function() {
var d = this.get('date'),
month = d.getMonth()+1,
day = d.getDate();
if (month<10) month = '0'+month;
if (day<10) day = '0'+day;
return [d.getFullYear(), month, day].join('-');
}
});
var C = Backbone.Collection.extend({
model: M
});
您的视图可能看起来像
var V = Backbone.View.extend({
render: function() {
var rows;
rows = this.collection.chain().groupBy(function (m) {
return m.day();
}).map(function (models, dt) {
// you would use a template here
// hard coded strings will do for now
var html = '<div class="day">' + dt + '</div>';
_.each(models, function (m) {
html+= '<div class="message">' + m.get('text') + '</div>';
});
return html;
}).value();
this.$el.html(rows.join(''));
}
});
还有一只小提琴
http://jsfiddle.net/nikoshr/swbm8ax5/4/