Skip to content

Instantly share code, notes, and snippets.

@ianstormtaylor
Forked from szimek/backbone_extensions.js
Created April 30, 2012 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianstormtaylor/2558515 to your computer and use it in GitHub Desktop.
Save ianstormtaylor/2558515 to your computer and use it in GitHub Desktop.
Mongo-style reduce for Backbone collections.
// 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