In 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 whenModels
are added or removed from thatCollection
or when Models in aCollection
are modifiedCollections
simplifies and encapsulates the logic for communicating with the server
We 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...