2012-04-04 173 views
0

我将模型发送到模板。该模型有一个集合。在模板我赞同一些变量和函数:集合在模板中不起作用

console.log(comments); 
console.log(_.size(comments)); 
console.log(comments instanceof App.Collections.Comments); 
console.log(_.pluck(comments, 'created')); 
_.each(comments, function(com) { 
    console.log(com); 
}); 

前三的工作,但最后两个下划线功能没有。 Pluck给出3个未定义的值,每个值都不重复。

Object { length=3, models=[3], _byId={...}, more...} 
3 
true 
[undefined, undefined, undefined] 

如何获得下划线功能?

回答

1

Backbone collections have some Underscore methods mixed in so you你可以直接使用下划线方法的集合实例:

console.log(comments.pluck('created')); 
comments.each(function(com) { console.log(com) }); 

演示:http://jsfiddle.net/ambiguous/3jRNX/

这一个:

console.log(_.size(comments)); 

正常工作对你,因为_.size看起来是这样的:

_.size = function(obj) { 
    return _.toArray(obj).length; 
}; 

_.toArray调用t他收集的toArray

// Safely convert anything iterable into a real, live array. 
_.toArray = function(iterable) { 
    if (!iterable)    return []; 
    if (iterable.toArray)   return iterable.toArray(); 
    if (_.isArray(iterable))  return slice.call(iterable); 
    if (_.isArguments(iterable)) return slice.call(iterable); 
    return _.values(iterable); 
}; 

其解开收集的数据给你正确的长度。以上摘自1.3.1来源,current Github master version_.size有不同的实现,因此您的_.size调用在升级过程中可能会中断。

+0

保存我的一天!日Thnx! – GijsjanB 2012-04-04 09:50:13