【问题标题】:Getting the sum of a collection (all models) with backbone.js使用backbone.js 获取集合(所有模型)的总和
【发布时间】:2011-10-11 06:15:41
【问题描述】:

我只是在学习骨干。我有以下

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 始终为空,但 items 始终正确。有什么想法吗?

我知道我的集合正在运行,因为其中有很多项目,但我需要将集合中每个项目的所有 CPU 加起来以作为页面摘要。

对于那些知道 todos 示例 http://documentcloud.github.com/backbone/docs/todos.html 的人,我有一个非常相似的设置。

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

    这是我知道的最好方法:

    cpuTotal: function() {
        return this.reduce(function(memo, value) { return memo + value.get("cpu") }, 0);
    }
    

    这是jsFiddle of the solution

    【讨论】:

    【解决方案2】:

    我相信您的问题是“this”可能会或可能不会引用您的集合实例,具体取决于您是否丢失了绑定(例如,如果 cpuTotal 作为函数调用中的参数传递)。您可以在初始化函数中更改将集合绑定到 cpuTotal 函数。我还没有对此进行测试,但请尝试一下(感谢@Brian 推荐 reduce):

    window.ServerList = Backbone.Collection.extend({
    
        model: Server,
    
        initialize: function() {
            _.bind(this.cpuTotal, this); // From Underscore.js
        },
    
        cpuTotal: function(){
            return this.reduce(function(memo, value) { return memo + value.get("cpu") }, 0);
        }
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-30
      • 2012-01-04
      • 1970-01-01
      • 2013-07-10
      • 2012-07-08
      • 2011-11-08
      • 1970-01-01
      • 2011-10-31
      相关资源
      最近更新 更多