Getting collection amount (all models) using backbone.js

I just study the highway. 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 call this from a rendering 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 the elements are always correct. Any ideas?

I know that my collection works because I have many elements, but I need to add the entire processor from each element to the collection for page summary.

For those who know the todos example http://documentcloud.github.com/backbone/docs/todos.html I have a very similar setup.

+8
javascript
source share
2 answers

Here is the best way to find out how:

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

Here is the jsFiddle solution .

+18
source share

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

All Articles