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

时间:2012-08-06 19:37:45

标签: javascript backbone.js

我正在尝试跟踪应用程序中的所有僵尸,并更好地了解事件绑定是如何发生的。 我有一个视图,将其集合"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被执行了两次。 我查看了类似的问题here,但它有所不同,因为我使用的是add事件,而不是change

3 个答案:

答案 0 :(得分:1)

您是否实例化了两次视图?它可能有两种不同的观点。

答案 1 :(得分:1)

我认为您正在调用渲染两次。

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/

答案 2 :(得分:0)

事实证明,通过Event Aggregator对render进行了额外的绑定。它是由另一位开发人员添加的。

相关问题