Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

javascript - How to find a model from a collection according to some attribute other than the ID?

I have a model with several object:

//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"});

and also, I will add these friends object to a collection:

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

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

and now I want to get a model according to the name of the Friend. I know that I can add an ID attribute to achieve this. But I think there should have some more simple way to do this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For simple attribute based searches you can use Collection#where:

where collection.where(attributes)

Return an array of all the models in a collection that match the passed attributes. Useful for simple cases of filter.

So if friends is your Friends instance, then:

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

There's also Collection#findWhere (a later addition as noted in the comments):

findWhere collection.findWhere(attributes)

Just like where, but directly returns only the first model in the collection that matches the passed attributes.

so if you're only after one then you can say things like:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...