Chapter 4. Organizing Models with Collections

In this chapter, we'll learn how to do the following:

  • Create new Collection subclasses
  • Add and remove Models from a Collection
  • Trigger other code in response to changes in the Collection
  • Store and retrieve Collections of Models to and from a remote server
  • Sand index the Models of a Collection
  • Take advantage of the the convenience methods borrowed from Underscore

Working with Collections

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 on
  • Collections allows other code to listen for and respond when Models are added or removed from that Collection or when Models in a Collection are modified
  • Collections 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 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
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.46.18