Skip to content

Instantly share code, notes, and snippets.

@ixisio
Last active December 16, 2015 03:59
Show Gist options
  • Save ixisio/5373528 to your computer and use it in GitHub Desktop.
Save ixisio/5373528 to your computer and use it in GitHub Desktop.
Filter Backbone.Collection items by more that one attribute..
// @deprected
// This GIST is deprected!
//_.findWhere() is exactly what you're searching for ;-)
// Example:
// collection.findWhere({
// color: 'red',
// brand: 'vw'
// })
// Backbone.Collection.getByAttrs
// Filter items by more that one attribute
// Currently is not possible to filter more
// than 2 pairs of value's.
// Returns[Array] of models which fulfill the
// filter requirements.
//
// @todo: Check for more that only two pairs.
// @todo: Change parameter-type from Array (of Objects)
// to Object (of Objects).
//
// Example:
// collection.getByAttrs([
// {color: 'red'},
// {brand: 'vw'}
// ]);
//
getByAttrs : function(attrs) {
var
_opts = { attr : [], val : [] },
_this = this,
_matched = function(attr, val) {
return attr == val ? true : false;
}
_(attrs).each(function(v) {
_opts.attr.push(_.keys(v)[0]);
_opts.val.push(_.values(v)[0]);
});
return this.filter(function(model) {
return
_matched(model.get(_opts.attr[0]), _opts.val[0]) &&
_matched(model.get(_opts.attr[1]), _opts.val[1]);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment