主干.js绑定到集合“添加”呈现视图两次

Backbone.js Binding to collection "add" renders view twice

本文关键字:视图 两次 绑定 js 集合 添加 主干      更新时间:2023-09-26

我正在尝试跟踪应用程序中的所有僵尸,并更好地了解事件绑定是如何发生的。我有一个视图,该视图将其集合"add"事件绑定到其render函数。

_.bindAll(this, "render");
this.collection.bind("add", this.render);

因此,如果我在我的渲染函数中记录一些东西,我可以在控制台中看到渲染在用户通过 UI 添加新模型后立即发生了两次。控制台输出如下所示:

rendering                                  index.js?body=1 (line 88)
POST http://localhost:3000/tasks           jquery.js?body=1 (line 8103)
rendering                                  index.js?body=1 (line 88)

我想知道为什么会这样。我知道模型只被添加到集合中一次,所以这让我认为该事件应该只触发一次。然后我不明白为什么render被处决了两次。我在这里看过类似的问题,但它是不同的,因为我使用的是add事件而不是change

您是否实例

化了两次视图?可能是两种不同的视图。

我认为您调用了两次渲染。

Yoy 正在做这样的事情:

var yourView = new YourDefinedView();
yourView.render(); // this is your manual call to render
//here you call to the server and when data arrives is the second render
this.collection.fetch();

我不认为渲染是集合收到新项目时绑定的最佳方法。

检查此示例我们如何绑定特定事件以将项目从集合添加到视图:http://danielarandaochoa.com/backboneexamples/blog/2012/02/22/real-world-usage-of-a-backbone-collection/

事实证明,通过事件聚合器render有一个额外的绑定。它是由另一个开发人员添加的。