总和 Backbone Collection
Sum Backbone Collection
我已经在 Whosebug 中阅读了一些主题,但我没有找到解决问题的方法...
我想将我所有模型中的 'progress' 字段求和到 collection...
所以在我的 collection 文件中我有:
progressTotal: ->
total = _.reduce(@, ((memo, value) ->
memo + value.get('progress')
), 0)
return total
但我发现该值未定义...为什么?我从这里获得灵感:Getting the sum of a collection (all models) with backbone.js 但解决方案对我不起作用。
有什么建议吗?谢谢
编辑: 好像 progress 是一个字符串...但在我的数据库中是一个整数。
您应该将 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)
我已经在 Whosebug 中阅读了一些主题,但我没有找到解决问题的方法... 我想将我所有模型中的 'progress' 字段求和到 collection... 所以在我的 collection 文件中我有:
progressTotal: ->
total = _.reduce(@, ((memo, value) ->
memo + value.get('progress')
), 0)
return total
但我发现该值未定义...为什么?我从这里获得灵感:Getting the sum of a collection (all models) with backbone.js 但解决方案对我不起作用。
有什么建议吗?谢谢
编辑: 好像 progress 是一个字符串...但在我的数据库中是一个整数。
您应该将 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)