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

馋奶兔 提交于 2019-11-28 04:28:50
Jani Hartikainen

Backbone collections support the underscorejs find method, so using that should work.

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

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

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

You can call findWhere() on Backbone collections, that will return exactly the model you are looking for.

Example:

var lee = friends.findWhere({ name: 'Lee' });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!