Collections
Collections are ordered set of models
Hello world:
var Library = Backbone.Collection.extend({
model: Song
});
var songCollection = new Library([
{
artist: "Death Cab for Cutie",
title: "Codes & Keys"
},
{
artist: "Noisettes",
title: "Atticues"
}
]);
songCollection.models.length; // 2
You can add your custom model, if you don't Backbone will just use a generic Backbone model.In most cases you don't need to override the model on the collection. you can pass a single model or an array.
Add models to the collection:
// A
songColleciotn.add({
artist: "Noisettes",
title: "Cheap Kicks"
});
// B
songCollection.create({
artist: "The Damned",
title: "Jet Boy Jet Girl"
});
.create
will also post to the restful service.Polymorphic Models
The
model
property can be a function and follow multiple paths:
Backbone.Collection.extend{({
model: function() {
if(condition){
return BookModel;
} else {
return NovellaModel;
}
}
})
No typical use case.The model will also have
collection
property that points to the instance of the collection. So you can access the parent collection. caveat: models can belong to multiple collections, but only the first one is lister in the collection
property.remove()
Many of the methods are the same as in underscore (all of them that exist in underscore on arrays).
var lowBitrateSongs = songCollection.where({quality:poor})
songCollection.remove(lowBitrateSongs)
.where
is an alias to filter
Collection are ordered in the order they are added
But you can do
library(song_two, {at: 0});
which will add at the beginningYou can also do
library.pluck("title")
which will give back an array of song titles (["song one", "song two", "song three"]