强调每个方法都没有贯穿整个骨干集合

时间:2012-03-06 20:42:00

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

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

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

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

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? 我该如何调试呢?

感谢任何帮助!

2 个答案:

答案 0 :(得分:4)

蒂姆已经给出了一个很好的答案,但还有更好的方法:

Underscore的迭代方法已经是Backbone集合的一部分,这意味着代替

_.each(@.models, @sendDelete)

你可以简单地写

@each(@sendDelete)

它还负责将@models转换为数组,防止destroy()弄乱迭代。

您永远不必直接使用@models;它应被视为内部属性,如模型上的@attributes

答案 1 :(得分:3)

首先将集合复制到数组中。您正在从正在枚举的集合中删除。我不是咖啡剧本大师,但有点像:

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