Collections and Models

Every Collection class has a model property, which defaults to Backbone.Model. You can set this property by providing it as an option when you use extend to create your Collection subclass:

var Cats = Backbone.Collection.extend({model: Cat});
var cats = new Cats(); // cats.model == Cat

However, this model property doesn't actually limit the type of Model a Collection can hold, and in fact, any Collection can hold any type of Model:

var Cat = Backbone.Model.extend();
var Cats = Backbone.Collection.extend({model: Cat});
var Dog = Backbone.Model.extend();
var snoopy = new Dog({name: 'Snoopy'});
var cartoonCats = new Cats([snoopy]);
cartoonCats.models[0] instanceof Dog; // true

This is because the model property of a Collection is only used when new Models are created through the Collection. One way in which this can happen is when the Collection is initialized with an array of attributes, as shown in the following example:

var snoopyAttributes = {id: 'dog1', name: 'Snoopy'};
var cartoonCats = new Cats([snoopyAttributes]);
cartoonCats.models[0] instanceof Cat; // true

Another way in which a Collection's model property can be used is via the Collection's create method. Calling create on a Collection and passing it an attributes object is essentially the same as calling new Collection.model(attributes), except that after the provided attributes are converted into a Model, Backbone will add this Model to the Collection and then save it:

var cartoonCats = new Cats();
var garfield = cats.create({name: 'Garfield'}); // equivalent to:
// var garfield = new Cat({name: 'Garfield'});// cats.models.push(garfield);
// garfield.save();
..................Content has been hidden....................

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