Reputation: 3591
Help me. How get model from Collection by id?
var Sidebar = Backbone.Model.extend({});
var sidebar = new Sidebar;
var Library = Backbone.Collection.extend({})
lib=new Library();
lib.add(sidebar,{at: 234});
console.log(lib.get(234))//undefined ..Why??
Upvotes: 2
Views: 79
Reputation: 123423
You seem to be mixing id
and index
, which aren't interchangeable.
To retrieve by id
, you'll want to set it with the Model
:
var sidebar = new Sidebar({ id: 234 });
// ...
console.log(lib.get(234));
The index
is the placement within the collection:
lib.add(sidebar, { at: 0 });
console.log(lib.at(0)); // sidebar
console.log(lib.models); // Array: [ sidebar ]
console.log(lib.models[0]); // sidebar
Upvotes: 4
Reputation: 55740
Try this
var Sidebar = Backbone.Model.extend({
// Need to set this. Otherwise the model
// does not know what propert is it's id
idAttribute : 'at'
});
var sidebar = new Sidebar();
var Library = Backbone.Collection.extend({})
var lib=new Library();
// Set the Model
sidebar.set({at:234});
// Add it to the collection
lib.add(sidebar);
console.log(lib.get(234))
The way you were adding the collection will be spliced at that index
and the model inserted at that index. I don't think that is not what you want. So you need to set the attributes to the model first and then add it to the collection.
Upvotes: 0