Skip to content

Instantly share code, notes, and snippets.

@twalker
Last active December 22, 2015 10:38
Show Gist options
  • Select an option

  • Save twalker/6459782 to your computer and use it in GitHub Desktop.

Select an option

Save twalker/6459782 to your computer and use it in GitHub Desktop.
A filterable mixin for Backbone.Collection.
/**
* Filterable mixin for collections that need multiple filters applied simultaneously.
* Useful when the collection is in a grid with filter views.
*
* @example
* // require filterable and mix into the consuming collection.
* var MyCollection = Backbone.Collection.extend({
* // consuming collections are encouraged to expose custom filters.
* addTypeFilter: function(typeId){
* return this.addFilter('type', function(model){
* return model.get('type') === typeId;
* }
* });
*
* lodash.defaults(MyCollection.prototype, filterable);
*
* var myColl = new MyCollection();
* myColl.addTypeFilter('tasty');
*
* myColl.addFilter('big',function(model){
* return model.get('count') > 1000;
* });
*
* myColl.filtered();// return array of all big, and tasty models.
*
**/
define(function(require){
var lodash = require('underscore');
var filterable = {
// add a filter to a filters property with the provided key.
addFilter: function(key, fnFilter, options){
this.filters = this.filters || {};
this.filters[key] = fnFilter;
var silent = options && options.silent;
if(!silent) this.filtered();
return this;
},
// remove an existing filter by the provided key.
removeFilter: function(key, options){
if(this.filters[key]) delete this.filters[key];
var silent = options && options.silent;
if(!silent) this.filtered();
return this;
},
// remove all the filters from instance.
clearFilters: function(options){
this.filters = {};
var silent = options && options.silent;
if(!silent) this.filtered();
return this;
},
// return a fully filtered subset of models for the collection.
filtered: function(){
var filtered = this.applyFilters(this.models);
this.trigger('filter', filtered);
return filtered;
},
// loop through filters returning a subset that pass all filters.
applyFilters: function(models){
lodash.forOwn(this.filters, function(fnValue, key, list){
models = models.filter(fnValue);
}, this);
return models;
}
};
return filterable;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment