【问题标题】:underscore each method not running through the complete backbone collection下划线未通过完整主干集合运行的每个方法
【发布时间】:2012-03-08 02:14:10
【问题描述】:

我有一个表,当新项目添加到集合中时我正在填充该表,当从该集合中删除项目时,我会填充已删除的项目集合。

然后我有一个保存按钮,它触发集合上的保存/删除事件。

保存工作正常,但我的删除只有一半工作,我很困惑。

class MyApp.Collections.DeletedTasks extends Backbone.Collection
  model: MyApp.Models.Task

  destroy: () ->
    console.log('destroy the collection size: ' + @.models.length)
    _.each(@.models, @sendDelete)

  sendDelete: (model) ->
    console.log('deleting model with id: ' + model.get('id'))
    model.destroy()

控制台输出

Done with Adding/Updating Collections
destroy the collection size: 6
deleting model with id: KSc18d06fefddbebd2ade74bcab4c670c907
deleting model with id: KS07cb95935b1caf3817758739224a3e1a2f
deleting model with id: KS6f473b3e15740fe7c6c0909e14986700a9

发生了什么? 为什么它只做了3? 我该如何调试?

感谢任何帮助!

【问题讨论】:

    标签: javascript backbone.js coffeescript underscore.js each


    【解决方案1】:

    Tim 已经给出了很好的答案,但还有更好的方法:

    Underscore 的迭代方法已经是 Backbone 集合的一部分,也就是说,不是

    _.each(@.models, @sendDelete)
    

    你可以简单地写

    @each(@sendDelete)
    

    这还负责将@models 转换为您的数组,防止destroy() 搞乱迭代。

    您永远不必直接使用@models;它应该被认为是一个内部属性,就像模型上的@attributes。

    【讨论】:

      【解决方案2】:

      首先将集合复制到一个数组中。您正在从正在枚举的集合中删除。我不是咖啡脚本大师,但类似:

      _.each(@.models.toArray(), @sendDelete)

      【讨论】:

      • _.each(@.toArray(), @sendDelete)
      • 很酷——感谢咖啡脚本更正:)(需要学习)
      猜你喜欢
      • 2023-04-06
      • 2012-10-16
      • 1970-01-01
      • 2012-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多