Iterating objects with underscore.js

15,798

Solution 1

this.collection is an instance while this.collection.each is a method that iterates the proper object under the covers which is the .models property of a collection instance.

With this said you can try:

_.each(this.collection.models, function(model){ console.log(model.get("description")); });

Which is completely pointless as this.collection.each is a function that does similar to:

function(){
return _.each.apply( _, [this.models].concat( [].slice.call( arguments ) ) );
}

So you might as well use this.collection.each ;P

Solution 2

Also, you could try...

_.each(this.collection.models, function(model){
    console.log(model.get("description"));
});
Share:
15,798
Industrial
Author by

Industrial

I just want to lie on the beach and eat hot dogs. That’s all I’ve ever wanted. Really.

Updated on June 04, 2022

Comments

  • Industrial
    Industrial almost 2 years

    So, I am learning out backbone.js and are currently iterating over some models in a view with the below example. The first snippet works, when the other underscore.js-based one doesn't. Why?

    // 1: Working
    this.collection.each(function(model){ console.log(model.get("description")); });
    
    // 2: Not working       
    _.each(this.collection, function(model){ console.log(model.get("description")); });
    

    What am I doing wrong, as I can't see it by myself?

  • Industrial
    Industrial over 12 years
    Thanks for your explanation of why it didn't work along with the solution!