Can I use Collection.get(id) to find a model within a Backbone.js collection by cid, for a model not yet saved to the server?
From the documentation, it seems like .get should find a model by either its id or cid. However, collection.get(cid)
doesn't find the model, whereas this does, collection.find(function(model) {return model.cid===cid; })
. Presumably I'm overlooking something basic.
var Element = Backbone.Model.extend({});
var Elements = Backbone.Collection.extend({ model: Element });
var elements = new Elements(), el, cids = [];
for (var i=0; i<4; i++) {
el = new Element({name: "element"+i})
elements.add(el);
cids.push(el.cid);
}
console.log(cids);
el1 = elements.get(cids[0]);
console.log(el1); // undefined
el1a = elements.find(function(model) { return model.cid === cids[0]; });
console.log(el1a); // success