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

后端 未结 4 2181
陌清茗
陌清茗 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:45

    The simplest way is to use "idAttribute" option of Backbone Model to let Backbone know the that you want to use "name" as your Model Id.

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

    Now you can directly use Collection.get() method to retrieve a friend using his name. This way Backbone does not loop through all of your Friend models in the Collection but can directly fetch a model based on its "name".

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

提交回复
热议问题