To create a new collection "class":
var Books = Backbone.Collection.extend({
// books will be sorted by title
comparator: "title",
initialize: function(models, options) {
options = options || {};
// (Optional) you can play with the models here
_.each(models, function(model) {
// do things with each model
}, this);
this.customProperty = options.property;
},
});
All the properties are optional and are there only as a demonstration. A Backbone.Collection
can be used as-is.
Then using it is as simple as:
var myBookArray = [
{ id: 1, title: "Programming frontend application with backbone" },
{ id: 2, title: "Backbone for dummies" },
];
var myLibrary = new Books(myBookArray, {
property: "my custom property"
});
myLibrary.each(function(book){
console.log(book.get('title'));
});
Will output:
Programming frontend application with backbone
Backbone for dummies