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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8493130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:13:39  来源:igfitidea点击:

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

javascriptbackbone.js

提问by Thomas Hunter II

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? I figure the worst I could do would be to iterate over each item, .get('id'), and return that one.

从具有给定 id 值的集合中获取我想要的模型的最佳方法是什么?我认为我能做的最糟糕的事情是迭代每个项目,.get('id'),然后返回那个项目。

回答by nikoshr

Take a look at the get method, it may be of some help :)

看看 get 方法,它可能有一些帮助:)

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

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

getcollection.get(id)
Get a model from a collection, specified by an id, a cid, or by passing in a model.

get collection.get(id)
从集合中获取模型,由 id、cid 指定,或通过传入模型。

回答by Nenotlep

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(). Something like this might work:

如果您的数据要求您使用不同类型的密钥或与at()getByCid()或不能很好地配合的集合,get()则还有where(). 像这样的事情可能会奏效:

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