Filtering a collection is a fairly simple concept; here we want to get a part of the data based on a certain criteria. For example, if you have a list of items and you want to filter the list to only show a subset of all the items, you filter the attached collection. By default, Backbone provides some built-in functions that take care of basic filtering. The two methods where()
and findWhere()
produce similar functionality, though findWhere()
only returns the first model that matches the condition.
The
where()
method accepts a set of model attributes and returns an array of the matched models.
var users = new Backbone.Collection([ { name: 'John', company: 'A' }, { name: 'Bill', company: 'B' }, { name: 'Rick', company: 'A' } ]); users.where({ company: 'A' });
The result will be an array of two models that have A
as their company. However, note that filtering the collection does not change the original collection data at all; instead...