2011-12-07 70 views
9

所以,我正在学习backbone.js,并且正在使用下面的示例在视图中的某些模型上进行迭代。第一个代码段可以工作,但其他基于underscore.js的代码不会。为什么?使用underscore.js迭代对象

// 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")); }); 

我做错了什么,因为我自己看不到它?

+2

是否有*发生?控制台中是否有错误? – Pointy

+0

编号#2静默执行,没有任何输出到控制台。 – Industrial

回答

22

this.collection是一个实例,而this.collection.each是一个迭代集合实例的.models属性下的适当对象的方法。

与此说,你可以尝试:

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

这是因为this.collection.each完全没有意义的是,做类似的功能:

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

所以你还不如用this.collection.each,P

+1

感谢您解释为什么它没有与解决方案一起工作! – Industrial

2

另外,您可以尝试...

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