Last active
December 10, 2015 08:18
-
-
Save benshimmin/4406368 to your computer and use it in GitHub Desktop.
Fun with Backbone.Collection and _.map
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's `where` is very useful for quickly selecting | |
# parts of a Collection, and it returns an array. But an array of | |
# Backbone.Models isn't terribly helpful if you want to insert that | |
# into a template which expects an array of raw objects. This might help | |
# you a little, though: | |
collectionToRaw = (collection, key) -> | |
_.map (collection.where "type" : key), (filtered) -> | |
filtered.toJSON() | |
# Assuming you have a simple Backbone.Model with a `type` attribute, | |
# and a collection called `myCollection` of these models, some which | |
# are `foo` and some `bar`, you can get an array of raw objects who | |
# are of type `foo` and a second of type `bar` like this: | |
data = | |
"foo" : collectionToRaw(myCollection, "foo") | |
"bar" : collectionToRaw(myCollection, "bar") | |
# You can then pass this into your template: | |
template = MyTemplate(data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An alternative (and perhaps nicer) way of doing this would probably be:
Backbone.Collection::toRaw = (key) -> _.map (@where "type" : key), (filtered) -> filtered.toJSON()
And then you can say:
myCollection.toRaw("foo")
to get an array of raw
foo
objects.