Home > Software design >  How to sum the values of a ko observable
How to sum the values of a ko observable

Time:02-02

Updating a really old application. Rails 3.22.xx -> 4.2.xx

This code use to work

ko.observable(ko.utils.arrayMap(@posts(), (page) -> page.unread_count()).sum())

It would return a number of the total, something like 15.

After upgrading to Rails 4.2 it returns

Uncaught TypeError: ko.utils.arrayMap(...).sum is not a function

I'm not sure how to get this so I can just return a sum of that value. If I remove the sum it returns an array of all the values, which is something like 1,0,0,0,10,0,20. It seems I need this value to sum though because it is being called from the view as a method, so If I just add a for loop and add all these up and then assign then to the variable the view still breaks.

CodePudding user response:

I don't know anything about rails, so not sure why it broke while updating... but I do know sum is not a default array method in javascript.

I propose you try and replace it with a reduce:

[1,0,0,0,10,0,20].reduce((a, b) => a   b, 0) // returns 31

You can also skip the map operation by summing like so:

posts().reduce(
  (total, post) => total   post.unread_count(),
  0
)

CodePudding user response:

You don't really need to use knockout utils anymore, all browsers implement Array.prototype.map:

ko.observable(@posts().map((page) -> page.unread_count()).reduce((x, y) -> x   y, 0)))

or in plain javascript

ko.observable(this.posts().map(function(page) {
  return page.unread_count()
}).reduce(function(x, y) {
  return x   y
}, 0)))
  •  Tags:  
  • Related