Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For Loop over Backbone Collection

Fairly new to backbone, so this is a really basic question. I have a Backbone collection passed into a function and I can prove that it has been passed and that the models in the collection have ids.

Here's how I'm setting the ids -

convertToMapObjects: (results)  =>
   objectList = new ObjectList()
   results.each(result)->
    testObj = new TestObject()
    testObj.set
      id = result.get("id")
    objectList.add(testObj)

And in another function ( accessed through making the model trigger an event) -

getIds: (objects) =>
ids = (object.id for object in objects) 

I think the issue may be because of how I'm iterating through the collection because when I tried doing

for object in objects
   console.log(object)

I saw two undefineds. Is this correct? If so, why can't I use a for loop to go through a backbone collection? Also, is there a way I could do so?

like image 217
praks5432 Avatar asked Jul 30 '12 17:07

praks5432


2 Answers

A Backbone collection is not an array so for ... in won't produce the results you're expecting. You want to look at the collection's models property if you want to use a simple loop.

However, Backbone collections have various Underscore methods mixed in:

Underscore Methods (28)

Backbone proxies to Underscore.js to provide 28 iteration functions on Backbone.Collection. They aren't all documented here, but you can take a look at the Underscore documentation for the full details…

  • forEach (each)
  • ...

So you can use map or pluck if you'd like to avoid accessing the models property:

ids = objects.map (m) -> m.id
ids = objects.pluck 'id'

The pluck method is, more or less, just a special case of map but collections implement a native version rather than using the Underscore version so that they can pluck model attributes rather than simple object properties.

like image 138
mu is too short Avatar answered Oct 14 '22 14:10

mu is too short


You want to loop over the models property of the collection, not the collection object itself.

like image 25
Colin Brock Avatar answered Oct 14 '22 14:10

Colin Brock