/ underscore

How to use underscore functions with Backbone collections

Today I'd like to talk about an issue I've recently encountered while working on Backbone collection. The issue can be rephrased into how to use underscore collection functions in Backbone collections without getting an error.

I was trying to use the underscore functions _.each() and _.map() on a Backbone collection but I was getting undefined.

My code looked something like this:

_.each(myCollection, function(model){

The result? model is undefined.

It turns out it's not hard to solve at all, but while searching on Google I had the impression there are many others who have been confused by this.

Some Background

Underscore collection functions are pretty much what Underscore is famous for. These are functions like each, map, reduce, shuffle, etc..

Backbone collections are groups of related backbone models.

How I solved it

An instance of a Backbone collection is an object, not an array. So you can't simply pass them into Underscore functions like you would with arrays.

The advantage though is that Backbone is integrated with Underscore so you can simply do:


Easy enough,right?
The above would be the preferred solution. However, there is also another way. If you'd really really prefer to use underscore with the usual syntax, you could also access the array associated with the collection by accessing its .models property in this way:

_.each(myCollection.models, function(model){
Marco Viappiani

Marco Viappiani

In this blog I like to talk about my experiences with software development, triathlon and more.

Read More