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

后端 未结 4 2174
陌清茗
陌清茗 2020-12-08 00:09

I have a model with several object:

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

//objects
va         


        
4条回答
  •  太阳男子
    2020-12-08 00:53

    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' });
    

提交回复
热议问题