Getting the sum of a collection (all models) with backbone.js

后端 未结 2 795
心在旅途
心在旅途 2021-01-12 07:20

I\'m just learning backbone. I have the following

window.ServerList = Backbone.Collection.extend({

    model: Server,

    cpuTotal: function(){
        if          


        
相关标签:
2条回答
  • 2021-01-12 07:34

    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 讨论(0)
  • 2021-01-12 07:49

    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.

    0 讨论(0)
提交回复
热议问题