In addition to passing in Models
or attributes
when we first create a Collection
, we can also add individual Models
or attributes
, or arrays of Models
or attributes
, to a Collection
via the add
method:
var cats = new Backbone.Collection(); cats.add({name: 'Garfield'}); cats.models[0] instanceof Cat; // true
Similar to create
, the add
method will use the Collection's model
property to create the resulting Models
. If instead you want to replace all the existing Models
in a Collection
rather than add more, you can use the reset
method, as shown here:
var cats = new Backbone.Collection([{name: 'Garfield'}]); cats.reset([{name: 'Heathcliff'}]); cats.models[0].get('name'), // "Heathcliff" cats.length; // 1, not 2, because we replaced Garfield with Heathcliff
3.15.22.160