In order to get or remove specific Models
from a Collection
, Backbone needs to know how to index these Models
. Backbone does this in two ways:
Using the Model's
id
property, if any (which, as we discussed in the previous chapter, can either be set directly or indirectly by setting the Model'sidAttribute
property)Using the Model's
cid
property (which all Models have)
When you add a Model
or attributes
to a Collection
, Backbone uses both of the preceding forms of identification to register the Model
in the Collection's _byId
property. _byId
is yet another one of Backbone's hidden properties, but it's a private
property as well (because its name is prefixed by _
). This means that, even more so than with other hidden properties, you should avoid using _byId
directly and instead use it indirectly through methods such as get
. The get
method returns the Model
with the provided ID (if any) by using _byId
:
var garfield = new Cat({id: 'cat1', name: 'Garfield'}); var cats = new Backbone.Collection...