モデルのコレクションをレンダリングする基本的なbackbone.jsアプリがあります。最後のモデルのみをレンダリングするように変更し、モデルの総数の数値も表示したいと思います。これまでの私のコードは次のとおりです。
var Thing = Backbone.Model.extend({
});
var ThingView = Backbone.View.extend({
el: $('body'),
template: _.template('<h3><%= title %></h3>'),
render: function(){
var attributes = this.model.toJSON();
this.$el.append(this.template(attributes));
}
});
var ThingsList = Backbone.Collection.extend({
model: Thing
});
var things = [
{ title: "Macbook Air", price: 799 },
{ title: "Macbook Pro", price: 999 },
{ title: "The new iPad", price: 399 },
{ title: "Magic Mouse", price: 50 },
{ title: "Cinema Display", price: 799 }
];
var thingsList = new ThingsList(things);
var ThingsListView = Backbone.View.extend({
el: $('body'),
render: function(){
_.each(this.collection.models, function (things) {
this.renderThing(things);
}, this);
},
renderThing: function(things) {
var thingView = new ThingView({ model: things });
this.$el.append(thingView.render());
}
});
var thingsListView = new ThingsListView( {collection: thingsList} );
thingsListView.render();