简体   繁体   English

如何通过其ID从Backbone.js集合中获取模型?

[英]How do I get a model from a Backbone.js collection by its id?

In my app, everything I do with data is based on the primary key as the data is stored in the database. 在我的应用程序中,我对数据所做的一切都基于主键,因为数据存储在数据库中。 I would like to grab a model from a collection based on this key. 我想从基于此键的集合中获取模型。

Using Collection.at() requires the array index, Collection.getByCid() requires the client ID that backbone randomly generates. 使用Collection.at()需要数组索引,Collection.getByCid()需要骨干随机生成的客户端ID。

What is the best way to grab the model I want from the collection with the given id value? 从具有给定id值的集合中获取我想要的模型的最佳方法是什么? I figure the worst I could do would be to iterate over each item, .get('id'), and return that one. 我认为我能做的最糟糕的事情就是迭代每个项目.get('id'),然后返回那个项目。

Take a look at the get method, it may be of some help :) 看看get方法,它可能会有所帮助:)

http://backbonejs.org/#Collection-get http://backbonejs.org/#Collection-get

get collection.get(id) get collection.get(id)
Get a model from a collection, specified by an id, a cid, or by passing in a model. 从集合中获取模型,由id,cid或传入模型指定。

If your data requires you to use a different kind of key or a set that doesn't mesh well with at() , getByCid() or get() , there is also where() . 如果您的数据要求您使用不同类型的键或与at()getByCid()get()不能很好地getByCid() ,那么还有where() Something like this might work: 像这样的东西可能会起作用:

window.lib = new Library;
window.lib.fetch([
    success: function(model, response) {
        console.log(window.lib.where({'BookID':488, 'Rev':2, 'Status':'Active'});
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM