使用backbone.js 获取集合(所有模型)的总和 [英] Getting the sum of a collection (all models) with backbone.js
问题描述
我只是在学习骨干.我有以下
I'm just learning backbone. I have the following
window.ServerList = Backbone.Collection.extend({
model: Server,
cpuTotal: function(){
if (!this.length) return 0;
/*
* NOT SURE HOW TO SUM THEM
* this.get('cpu') is an integer for each of the collections
*/
return this.get('cpu');
}
});
我从这样的视图的渲染方法中调用它
I'm calling this from the render method of a view like this
window.AppView = Backbone.View.extend({
// ....
render: function(){
var total_cpu = ServerList.cpuTotal();
var items = ServerList.length;
}
});
变量 total_cpu 总是空的,但 items 总是正确的.有什么想法吗?
The variable total_cpu is always empty but items is always correct. Any ideas ?
我知道我的集合正在运行,因为我有很多项目,但我需要将集合中每个项目的所有 CPU 相加以获取页面摘要.
I know my collection is working as I have plenty of items in there, but I need to add up all the CPU's from each item in the collection for the page summary.
对于那些知道 todos 示例的人 http://documentcloud.github.com/backbone/docs/todos.html 我有一个非常相似的设置.
For those who know the todos example http://documentcloud.github.com/backbone/docs/todos.html I have a very similar setup.
推荐答案
这是我所知道的最好方法:
Here is the best way I know how:
cpuTotal: function() {
return this.reduce(function(memo, value) { return memo + value.get("cpu") }, 0);
}
这是一个 jsFiddle 的解决方案.
这篇关于使用backbone.js 获取集合(所有模型)的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!