最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Iterating objects with underscore.js - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Dec 17, 2011 at 20:48 Andreas Köberle 111k58 gold badges280 silver badges307 bronze badges asked Dec 7, 2011 at 19:25 IndustrialIndustrial 42.8k71 gold badges201 silver badges292 bronze badges 2
  • 2 Does anything happen? Are there errors in the console? – Pointy Commented Dec 7, 2011 at 19:29
  • No. #2 executes silently without any output to the console. – Industrial Commented Dec 7, 2011 at 19:52
Add a comment  | 

2 Answers 2

Reset to default 24

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

Also, you could try...

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

评论列表(0)

  1. 暂无评论