如何在 backbone 中跟踪事件触发器(为集合中的每个模型添加触发器)

How to trace an event trigger in backbone (add triggered for every model in collection)

我在 Backbone 视图中有一些意外行为,"add" 正在为获取的集合中的每个模型触发,但我希望只是同步。所以我知道发生了一些有趣的事情,但我无法检测它是什么,因为代码涉及很多文件。

有人对我如何调试 where/what 触发添加有什么建议吗?或者当我只是获取集合时,甚至是什么可能导致每个模型都触发添加?

例如,当我运行:

@listenTo @collection, 'add', @adding
@listenTo @collection, 'sync', @synching

adding: -> console.log 'adding'
synching: -> console.log 'synching'

我 'render' 记录了 20 次(集合中的模型数),但 'synching' 只记录了一次,正如预期的那样。

常规 Backbone.Collection.fetch(...) 使用 Collection.set(...) 填充模型。 Here's the line from the source 显示代码。 Collection.set(...) 为返回的每个模型触发 add 个事件。

如果您实际上正在获取 "initial" 模型集,您可能希望在返回数据时 "reset" 该集合:

var collection = new MyCollection();
collection.fetch({ reset: true });

这将导致集合在返回数据时使用 reset,而不会触发 add 事件。 Here's the source 对于 reset(...);请注意它使用 this.add(...) 但传入 silent 标志。因此,您将获得一个 reset 事件,然后是一个 sync 事件。