Skip to content

Instantly share code, notes, and snippets.

@benshimmin
Last active December 10, 2015 08:18
Show Gist options
  • Save benshimmin/4406368 to your computer and use it in GitHub Desktop.
Save benshimmin/4406368 to your computer and use it in GitHub Desktop.
Fun with Backbone.Collection and _.map
# 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)
@benshimmin
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment