如何根据ID之外的某些属性从集合中查找模型?

Ana*_*nar 47 javascript backbone.js backbone.js-collections

我有一个带有几个对象的模型:

//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"});
Run Code Online (Sandbox Code Playgroud)

而且,我将这些朋友对象添加到一个集合:

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

Friends.add(f1);
Friends.add(f2);
Friends.add(f3);
Run Code Online (Sandbox Code Playgroud)

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

mu *_*ort 85

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

哪里 collection.where(attributes)

返回集合中与传递的属性匹配的所有模型的数组.适用于简单的情况filter.

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

var lees = friends.where({ name: 'Lee' });
Run Code Online (Sandbox Code Playgroud)

还有Collection#findWhere(如评论中所述,后来添加):

findWhere collection.findWhere(attributes)

就像在哪里一样,但只直接返回集合中与传递的属性匹配的第一个模型.

所以,如果你只是在一个之后,那么你可以这样说:

var lee = friends.findWhere({ name: 'Lee' });
Run Code Online (Sandbox Code Playgroud)

  • 或者使用`friends.findWhere({name:"Lee"})`应该只获得匹配的集合中的第一个模型(因此有效地保存了一个`[0]`),但我怀疑它需要Backbone> 1.0 0.0 (6认同)

Jan*_*nen 64

Backbone集合支持underscorejs find方法,因此使用它应该有效.

things.find(function(model) { return model.get('name') === 'Lee'; });
Run Code Online (Sandbox Code Playgroud)


cod*_*erC 6

最简单的方法是使用Backbone Model的"idAttribute"选项让Backbone知道您要使用"name"作为Model Id.

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

现在,您可以直接使用Collection.get()方法使用他的名称检索朋友.这样Backbone不会遍历Collection中的所有Friend模型,但可以直接根据其"名称"获取模型.

var lee = friends.get('Lee');
Run Code Online (Sandbox Code Playgroud)


Sil*_*vee 5

您可以调用findWhere()Backbone集合,它将返回您正在寻找的模型.

例:

var lee = friends.findWhere({ name: 'Lee' });
Run Code Online (Sandbox Code Playgroud)