-->

如何找到一个集合的模式,根据比其他ID某个属性?(How to find a model from

2019-07-18 11:19发布

我有几个对象的模型:

//Model
Friend = Backbone.Model.extend({
    //Create a model to hold friend attribute
    name: null,
}); 

//objects
var f1 = new Friend({ name: "Lee" });
var f2 = new Friend({ name: "David"});
var f3 = new Friend({ name: "Lynn"});

而且,我会添加这些朋友反对集合:

//Collection
Friends = Backbone.Collection.extend({
    model: Friend,
});

Friends.add(f1);
Friends.add(f2);
Friends.add(f3);

现在我想根据朋友的名字得到一个模型。 我知道,我可以添加一个ID属性来实现这一目标。 但我认为应该有一些更简单的方法来做到这一点。

Answer 1:

骨干集合支持underscorejs find方法,因此使用,应该工作。

things.find(function(model) { return model.get('name') === 'Lee'; });


Answer 2:

对于简单的基于属性的搜索,你可以使用Collection#where

其中 collection.where(attributes)

返回匹配所传递的属性 ,一个集合中的所有型号的数组。 有用的简单的情况下filter

所以,如果friends就是你的Friends实例,那么:

var lees = friends.where({ name: 'Lee' });

还有Collection#findWhere (如在评论中所指出后面加):

findWhere collection.findWhere(attributes)

就像在哪里 ,而是直接返回只有第一个模式相匹配的传递属性的收藏。

所以,如果你只有一个是后话可以说这样的话:

var lee = friends.findWhere({ name: 'Lee' });


Answer 3:

最简单的方法是使用主干模型“idAttribute”选项,让骨干知道要使用“姓名”作为您的型号标识。

 Friend = Backbone.Model.extend({
      //Create a model to hold friend attribute
      name: null,
      idAttribute: 'name'
 });

现在,您可以直接使用Collection.get()方法使用他的名字来检索朋友。 这样,骨干不遍历所有的收藏您的朋友车型,但​​可以直接获取基于其“名”的典范。

var lee = friends.get('Lee');


Answer 4:

您可以拨打findWhere()上骨干的集合,将返回正是你正在寻找的模型。

例:

var lee = friends.findWhere({ name: 'Lee' });


文章来源: How to find a model from a collection according to some attribute other than the ID?