Iterating objects with underscore.js

拟墨画扇 提交于 2019-12-09 15:52:13

问题


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?


回答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




回答2:


Also, you could try...

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


来源:https://stackoverflow.com/questions/8421238/iterating-objects-with-underscore-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!