Created
March 17, 2012 00:11
-
-
Save edfuh/2053814 to your computer and use it in GitHub Desktop.
Hacky ass ways to filter 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
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