集合没有'不能在模板中工作
Collection doesn't work in template
我将模型发送到模板。该模型有一个集合。在模板中,我回显了一些变量和函数:
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');
相关文章:
- AngularJS UI路由器不能像ng路由器那样工作
- HTML5音频加载和播放获胜'我不能在iPad上工作
- JS可以在Chrome中工作,但不能在Firefox中工作
- javascript扫雷器floodfill算法不能正常工作
- JavaScript指令不能像我想象的那样工作
- Facebook登录按钮没有'不能在Firefox上工作
- jQuery Datepicker可以在Safari中工作,但不能在FF或Chrome中工作
- javascript没有´我不能在joomla 3.0中工作
- 用javascript将script元素附加到头部;铬不能工作
- jQuery函数不能只在一个页面上工作
- 为什么这个代码不能正常工作
- 为什么jquery悬停在jsfiddle中可以工作,而在我的html布局中却不能
- 为什么我的JavaScript在Safari上的严格模式下不能正常工作
- 为什么Turbolinks不能正常工作?Rails应用程序
- jQuery dosn'内联函数不能按预期工作
- 为什么这个javascript工作不能正确地分配.cells[] ?
- 谷歌应用引擎云端点:OAuth2不工作.不能加载api
- 输入焦点不工作/不能选择单选按钮-引导
- LocalStorage不能在iPhone上工作-不能在私人浏览
- 工作不能代替生活