我只是在学习 Backbone 。我有以下
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');
}
});
我是从这样的 View 的render方法调用的
window.AppView = Backbone.View.extend({
// ....
render: function(){
var total_cpu = ServerList.cpuTotal();
var items = ServerList.length;
}
});
变量total_cpu始终为空,但项始终正确。有任何想法吗 ?
我知道我的收藏集正在运行,因为其中有很多项目,但是我需要对集合摘要中每个项目的所有CPU进行总计。
对于那些知道待办事项示例http://documentcloud.github.com/backbone/docs/todos.html的人,我有一个非常相似的设置。
最佳答案
这是我知道的最好方法:
cpuTotal: function() {
return this.reduce(function(memo, value) { return memo + value.get("cpu") }, 0);
}
这是一个jsFiddle of the solution。
关于javascript - 使用 Backbone .js获取集合的总和(所有模型),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7722048/