获取集合与Backbone.js的总和(所有型号) [英] Getting the sum of a collection (all models) with backbone.js
问题描述
我刚学骨干。我有以下
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');
}
});
我是从这样的
window.AppView = Backbone.View.extend({
// ....
render: function(){
var total_cpu = ServerList.cpuTotal();
var items = ServerList.length;
}
});
变量total_cpu始终是空的,但项目始终是正确的。任何想法?
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.
对于那些谁知道待办事项例如<一个href=\"http://documentcloud.github.com/backbone/docs/todos.html\">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。
Here is a jsFiddle of the solution.
这篇关于获取集合与Backbone.js的总和(所有型号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!