[英]Collection doesn't work in template
I send a model to a template.我将 model 发送到模板。 The model has a collection.
model有收藏。 In the template I echo some variables and functions:
在模板中,我回显了一些变量和函数:
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);
});
The first three work, but the last two underscore functions don't.前三个有效,但后两个下划线函数无效。 Pluck gives 3x undefined and each doesn't iterate.
Pluck 给出 3x undefined 并且每个都不会迭代。
Object { length=3, models=[3], _byId={...}, more...}
3
true
[undefined, undefined, undefined]
How do I get the underscore functions to work?如何让下划线函数起作用?
You'll want to call pluck directly on the collection, as the Collection class supports it:您需要直接在集合上调用 pluck,因为集合 class 支持它:
http://documentcloud.github.com/backbone/#Collection-pluck http://documentcloud.github.com/backbone/#Collection-pluck
So instead of:所以不是:
_.pluck(comments, 'created')
You chould call:你可以打电话:
comments.pluck('created');
Backbone collections have some Underscore methods mixed in so you can use the Underscore methods directly on the collection instance: Backbone collections 混合了一些 Underscore 方法,因此您可以直接在集合实例上使用 Underscore 方法:
console.log(comments.pluck('created'));
comments.each(function(com) { console.log(com) });
Demo: http://jsfiddle.net/ambiguous/3jRNX/演示: http://jsfiddle.net/ambiguous/3jRNX/
This one:这个:
console.log(_.size(comments));
works fine for you because _.size
looks like this:对你很好,因为
_.size
看起来像这样:
_.size = function(obj) {
return _.toArray(obj).length;
};
and _.toArray
calls the collection's toArray
: _.toArray
调用集合的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);
};
which unwraps the collection's data to give you the correct length.它解开集合的数据以为您提供正确的长度。 The above is taken from the 1.3.1 source, the current Github master version 's
_.size
has a different implementation so your _.size
call is likely to break during an upgrade.以上内容取自 1.3.1 源代码, 当前 Github 主版本的
_.size
有不同的实现,因此您的_.size
调用可能会在升级过程中中断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.