13

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.

jsFiddle for example below

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

Backbone.js - id vs idAttribute vs cid

Community
  • 1
  • 1
prototype
  • 7,249
  • 15
  • 60
  • 94

1 Answers1

24

In backbone 0.9.9 (see changelog), they removed the .getByCid() method and folded that functionality directly into .get() -- if you're using below 0.9.9, you can use the .getByCid() method; I think they've since removed it from the docs to reflect the most current state of the library.

Edit:

See @Ferdinand Prantl's comment below for more detail, but passing the cid as the property of an object literal will accomplish what you're looking for here: .get({ cid: "xxx" }). My apologies for any confusion.

Bryan A
  • 3,598
  • 1
  • 23
  • 29
  • 5
    Use `.get({ cid: "..." })`. The `id` can be passed directly to the `get`, but `cid` has to be passed as an object literal. Actually, you can pass the `id` in an object literal too and have your code consistent. – Ferdinand Prantl Apr 13 '14 at 09:47
  • @Ferdinand Prantl, I've edited my answer. Thanks for clearing this up. – Bryan A Apr 14 '14 at 21:46