Sum Backbone Collection

时间:2015-04-02 20:56:55

标签: backbone.js coffeescript underscore.js backbone-collections

我已经在stackoverflow中阅读了一些主题,但我没有找到解决问题的方法...... 我想做进步的总和'将我所有模特中的字段变成一个集合...... 所以在我的收藏文件中我有:

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

但我得到的价值是未定义的......为什么?我从这里获得了灵感:Getting the sum of a collection (all models) with backbone.js但解决方案并不适合我。

有什么建议吗?谢谢

编辑:好像是进展是一个字符串......但在我的数据库中是一个整数。

1 个答案:

答案 0 :(得分:1)

您应该将models数组传递给reduce而不是集合,因此只需将@替换为@models

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

您也可以使用Backbone.Collection#reduce方法

progressTotal: ->
    return @reduce(((memo, value) ->
      memo + value.get('progress')
    ), 0)
相关问题