-
-
Save ianstormtaylor/2558515 to your computer and use it in GitHub Desktop.
Mongo-style reduce for Backbone collections.
This file contains hidden or 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
// Reduce collection using provided conditions | |
// e.g. FriendList.where({age: 30, gender: 'male'}) | |
// Returns object of the same "class", so it's possible to chain methods | |
Backbone.Collection.prototype.where = function(conditions) { | |
return new this.constructor(_(conditions).reduce(function(memo, value, key) { | |
memo = _(memo).filter(function(model) { | |
return model.get(key) === value; | |
}); | |
return memo; | |
}, this.models)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment