Skip to content

Instantly share code, notes, and snippets.

@edfuh
Created March 17, 2012 00:11
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 edfuh/2053814 to your computer and use it in GitHub Desktop.
Save edfuh/2053814 to your computer and use it in GitHub Desktop.
Hacky ass ways to filter backbone collections
Backbone.Collection.extend({
// #sadface
// collection.sadFilter().invoke('save') <- TypeError
sadFilter : function (m) {
return this.filter(function (m) {
return m.get('happiness') < 1
})
},
// First option
// Wrap in underscore object
// supports all underscore methods and all is joy
// but what if I want to "colleciton.coolFilter().get(23)"
// no dice
coolFilter : function () {
return _(this.filter(function (m) {
return m.get('coolnes') > 9000
}));
},
// Second option
// instantiate a new collection from this constructor
// _all_ underscore and collection models work
// !!! remember it's a clone of the original collection, not
// a reference. However, the models within the collection will
// still reference the originals
// ????
// profit
dopeFilter : function () {
return new this.constructor(this.filter(function (m) {
return m.get('dopeness') > 9000
}));
},
// variation on #2
radFilter : function () {
return (new this.constructor).reset(this.filter(function (m) {
return m.get('radness') > 9000
}));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment