1

I've already read some topics here in stackoverflow, but I didn't found a solution to my problem... I want do the sum of 'progress' field in all my models into a collection... So in my collection file I have:

  progressTotal: ->
    total = _.reduce(@, ((memo, value) ->
      memo + value.get('progress')
    ), 0)
    return total

But I get that value is undefined ... why ? I've taken inspiration from here: Getting the sum of a collection (all models) with backbone.js but the solution doesn't work for me.

Any suggestion ? thank you

EDIT: Seems like if progress is a string...but in my db is a integer.

Community
  • 1
  • 1
Riccardo
  • 363
  • 1
  • 5
  • 11

1 Answers1

1

You should pass an array of models to reduce instead of collection, so just replace @ with @models

progressTotal: ->
    total = _.reduce(@models, ((memo, value) ->
      memo + value.get('progress')
    ), 0)
    return total

you can also use Backbone.Collection#reduce method

progressTotal: ->
    return @reduce(((memo, value) ->
      memo + value.get('progress')
    ), 0)
Eugene Glova
  • 1,543
  • 1
  • 9
  • 12
  • I had already tried with the Backbone.Collection#reduce and I've also used your code, but when I do: console.log @milestones.progressTotal() I get NaN. – Riccardo Apr 02 '15 at 22:03
  • I've also tried to print the value directly in the function: https://gist.github.com/anonymous/30dde77281c813461a32 I always get NaN. – Riccardo Apr 02 '15 at 22:15
  • The answer is correct...I have a problem but it related to my collection...I will open a new question here on Stackoverflow if I didn't fix by myself. Thank you. – Riccardo Apr 02 '15 at 23:02