开发者

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;

     }
 });

The variable total_cpu is always empty but items is always correct. Any ideas ?

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.

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);
}

Here is a jsFiddle of the solution.


I believe your problem is that "this" may or may not refer the instance of your collection, depending on whether or not you've lost your binding (e.g. if cpuTotal is passed as an argument in a function call). You can change bind the collection to the cpuTotal function in the initialize function. I haven't tested this, but give it a try (kudos to @Brian for recommending 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);
    }

});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜