In this chapter, we'll learn how to do the following:
Collection
subclassesCollections
of Models
to and from a remote serverIn Backbone, Models may form the core of all data interaction, but you'll soon find that you need to work with multiple Models to do any real work, which is where the Collections
class comes in. Just as a Model wraps an object and provides additional functionality, Collections
wraps an array and offers several advantages over using the array directly:
Collections
uses Backbone's class system, making it easy to define methods, create subclasses, and so onCollections
allows other code to listen for and respond when Models
are added or removed from that Collection
or when Models in a Collection
are modifiedCollections
simplifies and encapsulates the logic for communicating with the serverWe can create a new Collection
subclass, as follows:
var Cats = Backbone.Collection.extend({ // The properties and methods of Cats would go here });
Once we've created a subclass, we can instantiate new instances of it using JavaScript's new
keyword, just as we did to create new Model
instances. Like Models, Collections have two optional arguments. The first argument is an initial array of Models
or Model
attributes, and the second argument is the Collection's options. If you pass in an array of Model
attributes, Backbone will convert them into Models for you, as follows:
var cartoonCats = new Cats([{id: 'cat1', name: 'Garfield'}]); var garfield = cartoonCats.models[0]; // garfield is a Model
Once a Collection
subclass has been created, it stores its Model in a hidden property called models
. Similar to attributes, models should not be used directly, and you should instead rely on the methods of Collection
to work with its Models. Backbone also provides a length
property on each Collection
, which is always set to the number of Models in the Collection
subclass:
var cartoonCats = new Cats([{name: 'Garfield'}, {name: 'Heathcliff'}]); cartoonCats.models.length; // 2, but instead you can do ... cartoonCats.length; // also 2
3.143.9.223