如何按id从集合中获取模型

How get model from Collection by id?

本文关键字:获取 模型 集合 何按 id      更新时间:2023-09-26

帮帮我。如何通过id从Collection中获取模型?

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??

您似乎在混合idindex,它们是不可互换的。

要通过id检索,您需要使用Model:进行设置

var sidebar = new Sidebar({ id: 234 });
// ...
console.log(lib.get(234));

index是集合中的位置:

lib.add(sidebar, { at: 0 });
console.log(lib.at(0));     // sidebar
console.log(lib.models);    // Array: [ sidebar ]
console.log(lib.models[0]); // sidebar

试试这个

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))

检查Fiddle

添加集合will be spliced at that index和在该索引处插入的模型的方式。我不认为那不是你想要的。因此,您需要先设置模型的属性,然后将其添加到集合中。