Search collection and retrieve model backbonejs

随声附和 提交于 2019-12-23 19:09:18

问题


I am trying to search a collection for a model attribute and then grab and return the entire model ?

var myModel = Backbone.Model.extend({
  defaults: {
      a: '',
      b: '',
      c: '',
      d: '',
      e: ''
  }
});

My collection has around 100 of myModels.

I am trying to search through the collection by a, find it and then return the entire myModel of a so I can access the other attributes ?


回答1:


If I understand your question correctly, you want to use the where method on Backbone collections, here in the docs:

http://backbonejs.org/#Collection-where

So, given an instance of MyCollection called myCollection that has MyModels in it, you can say:

var foundModels = myCollection.where({a:'some value'});

and foundModels will contain an array of the models you seek

BTW, if you are doing a more complex search, use the filter method instead, passing a function as the first argument that returns true on the desired match:

var modelsWhoseAStartsWithA = myCollection.filter(function(anyModel) {
    var startsWithA = new RegExp(/^[aA]/);
    return startsWithA.test(anyModel.get('a'));
});


来源:https://stackoverflow.com/questions/14450011/search-collection-and-retrieve-model-backbonejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!