Skip to content

Instantly share code, notes, and snippets.

@kristoferjoseph
Last active March 1, 2018 09:20
Show Gist options
  • Save kristoferjoseph/6120998 to your computer and use it in GitHub Desktop.
Save kristoferjoseph/6120998 to your computer and use it in GitHub Desktop.
Example Filterable Collection
// Collection of filter functions
filters: new Backbone.Collection(),
// Temporary collection used to apply the filters to
tempCollection: new Backbone.Collection(),
// Filter function for sub string in property
stringInPropertyFilterFunction: function (prop, str) {
return function (model) {
var lowerCaseProp = model.get(prop).toLowerCase();
return lowerCaseProp.indexOf(str.toLowerCase()) !== -1;
};
},
// Adds a filter function to the filters collection to be applied later
addFilter: function (obj) {
this.filters.add(obj);
return this.applyFilters();
},
// Applies all the existing filters to the data set and returns the results
applyFilters: function() {
var self = this,
tempCollection = this.tempCollection.reset(self.toJSON());
self.filters.each(function(filterModel) {
var filterFunction = self[filterModel.get('filterFunction')],
args = filterModel.get('args') || [];
if (filterFunction) {
tempCollection.reset(tempCollection.filter(filterFunction.apply(self, args)), {
'silent': true
});
}
});
return tempCollection.toJSON();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment