Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.Collection get model by id

I have a collection that fetches models from server.

This works, now I want to grab a model by its id with MyCollection.at(0) and I get:

child
_changes: Array[0]
_changing: false
_currentAttributes: Object
_events: Object
_hasComputed: true
_pending: false
_previousAttributes: Object
attributes: Object
_id: "50ef7a63b2a53d17fe000001"
author_name: "author name"
bookmark: ""
info: "bookmark description"
__proto__: Object
changed: Object
cid: "c26"
collection: child
view: child
__proto__: Surrogate

If I try to get the model by its id i get:

MyCollection.get("50ef7a63b2a53d17fe000001")
=> undefined

MyColleciton.get({_id:"50ef7a63b2a53d17fe000001"})
=> undefined

MyCollection.get({'_id':"50ef7a63b2a53d17fe000001"})
=> undefined

I don't get that - the docs say clearly that the .get() method will return the model if a model with the given id exists in that collection.

like image 463
Inoperable Avatar asked Jan 13 '13 02:01

Inoperable


People also ask

Does anyone use Backbone JS?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.

Which of the following is the correct syntax for creating Backbone collection with model model?

The Backbone. js collection models specify the array or models which are created inside of a collection. Syntax: collection.

Is Backbone a MVC?

Backbone is a JavaScript MVC library and that's a key difference. In the JavaScript MVC context, a framework usually means that you need to configure your code to get things done. Maybe you need to add some code to your HTML page, or give a page element a certain ID class name.


2 Answers

Have you set Model.idAttribute on the Model?

var Model = Backbone.Model.extend({
    idAttribute:"_id"
});

By default Backbone expects the id property be called id. When the idAttribute has been set, Backbone standardizes handling of ids so that model.id is always available, even if the id property is called something else. The original id property is available in the Model's attributes hash, and as such via the get methd. So:

model.id === model.get('_id') // -> true
like image 149
jevakallio Avatar answered Oct 04 '22 21:10

jevakallio


You can use the cid (client-side ID) attribute of the model as an argument to MyCollection.get(), which is guaranteed to exist from creation on. The documentation seems to think that will work, see http://backbonejs.org/#Collection-get.

like image 45
Rafe Kettler Avatar answered Oct 04 '22 20:10

Rafe Kettler