为什么在 Backbone.js 中第二次渲染后事件没有触发?
我正在 Backbone.js 创建一个应用程序,它有一个父视图和多个子视图。子视图包含它们监听并执行功能的链接。
父视图存储所有子视图的列表。在渲染函数中,计算完自己的 html 后,它会执行以下操作:
$(this.el).html(html);
for (var i = 0; i < this.views.length; i++){
$('.children', this.el).append(this.views[i].render().el);
}
解答:问题是我在渲染期间创建了链接。即在第一次渲染(从 init 调用)时,事件成功绑定到链接。但是,由于所有后续的 render 调用都会重新创建整个元素,因此新链接没有绑定到它的处理程序。这是通过 @Tom Tu 将 this.delegateEvents()
添加到渲染的解决方案解决的
I am creating an app in Backbone.js which has a parent and multiple child views. The child views contain links which they listen to and perform a function.
The parent stores a list of all of the children views. In the render function, after it is done computing its own html, it does the following:
$(this.el).html(html);
for (var i = 0; i < this.views.length; i++){
$('.children', this.el).append(this.views[i].render().el);
}
ANSWER: The problem was that I was creating the link during the render. I.e. on the first render (which was called from the init) the event successfully binded to the link. However, since all following calls of render recreate the whole element, the new link did not have the handler bound to it. This was solved via @Tom Tu solution of adding this.delegateEvents()
to the render
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能在某处使用 jquery
remove
函数从视图中删除子视图 - 它会自动删除绑定到元素 (this.el) 的所有事件 - 在events
中设置目的。您可以在渲染模板后在子视图的渲染中使用this.delegateEvents()
方法来重新绑定events
对象中设置的事件委托,或者使用 jquerydetach< /code> 方法从 DOM 中删除元素而不删除事件绑定(链接)。
delegateEvents
方法的成本相当高,因此我建议使用detach
方法来删除要重用的元素(如果您正在渲染长子视图列表) - 如果它只是不相关,则无关紧要一些观点。另一种可能性是您将
events
对象设置错误 - 很难从提供的代码量中看出,但我打赌第一个。You are probably using jquery
remove
function somewhere to remove the subviews from the view - it automatically removes all the events bound to the element (this.el) - set in theevents
object. You can either usethis.delegateEvents()
method in render of the subviews after you render template to rebind the event delegates set inevents
object or use jquerydetach
method instead to remove elements from DOM without removing event bindings (link). ThedelegateEvents
method is quite costly and thus i'd recommend thedetach
method for removing elements that you want to reuse if you are rendering long lists of subviews - irrelevant if it's just a couple of views.Other possibility is that you've set the
events
object wrong - hard to tell from the amount of code provided, but i bet on the first one.这是一个非常常见的挑战。对于这个问题的未来发现者,这里有一篇关于视图渲染的精彩文章:
http://ianstormtaylor.com/rendering-views-in-backbonejs-isnt-always-simple/
A really common challenge. For future finders of this question, here's a great article about view rendering:
http://ianstormtaylor.com/rendering-views-in-backbonejs-isnt-always-simple/