Last active
March 1, 2018 09:20
-
-
Save kristoferjoseph/6120998 to your computer and use it in GitHub Desktop.
Example Filterable Collection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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