Reputation: 2551
I have a basic backbone.js app that renders a collection of models. I would like to modify to render only the last model, and also display a number for the total number of models. Here is my code so far:
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();
Upvotes: 3
Views: 9561
Reputation: 371
I have tried using the collection.length
function but it kept on failing, but going to the basics helped:
To get the first Model I recommend:
var firstModel = Models.at(0);
alert(firstModel.get("attribute"));
To get the last Model on the collection of Models:
var lastModel = Models.pop();
var lastModelId = lastModel .get("id");
Upvotes: 1
Reputation: 21575
Get the last model from the collection using at()
:
// this.collection.length - 1 is the index of the last model in the collection
var last_model = this.collection.at(this.collection.length - 1);
Your render()
function would then look something like this:
render: function(){
var last_model = this.collection.at(this.collection.length - 1);
this.renderThing(last_model);
}
Get the total number of models in the collection using the length
property:
var total = this.collection.length;
Edited to add that Backbone offers a last()
method on each collection, courtesy of Underscore JS (thanks to @RocketR for pointing this out). So, the above could more easily be written as follows:
var last_model = this.collection.last();
Upvotes: 13