Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find model in Backbone.js collection by cid rather than id

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

like image 554
prototype Avatar asked Jan 25 '13 15:01

prototype


People also ask

How can we get the attribute value of a model in Backbone JS?

js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)

What is collections in Backbone JS?

Collections are ordered sets of Models. We just need to extend the backbone's collection class to create our own collection. Any event that is triggered on a model in a collection will also be triggered on the collection directly.

Why use Backbone js?

BackboneJS allows developing of applications and the frontend in a much easier way by using JavaScript functions. BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications.

What is Backbone framework?

Backbone. js is a model view controller (MVC) Web application framework that provides structure to JavaScript-heavy applications. This is done by supplying models with custom events and key-value binding, views using declarative event handling and collections with a rich application programming interface (API).


1 Answers

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.

like image 58
Bryan A Avatar answered Oct 14 '22 19:10

Bryan A