集合没有'不能在模板中工作

Collection doesn't work in template

本文关键字:工作 不能 集合      更新时间:2023-09-26

我将模型发送到模板。该模型有一个集合。在模板中,我回显了一些变量和函数:

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]

如何使下划线函数工作?

Backbone集合中混合了一些Undercore方法,因此您可以直接在集合实例上使用Undercore:

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;
};

并且CCD_ 2调用集合的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源代码,当前Github主版本的_.size有一个不同的实现,因此您的_.size调用可能会在升级过程中中断。

您需要直接在集合上调用pulture,因为collection类支持它:

http://documentcloud.github.com/backbone/#Collection-拔出

所以不是:

_.pluck(comments, 'created')

您可以拨打:

comments.pluck('created');