为什么每次重新渲染父视图时都需要重新委托子视图的事件?

Why do I need to re-delegate the events of a child view every time the parent view is being re-rendered?

当然,这取决于您如何重新呈现父视图。父视图在初始化阶段实例化它的所有子视图,并在呈现模板后简单地附加 them/replaces 一个元素。例如,这就是我在渲染方法中的做法:

this.$('.InputSearch').replaceWith(this.inputSearchView.$el);

所以this.inputSerchView是在初始化方法中被影响的实例

问题是在上面的行执行后,事件回调在 inputSearchView 中不再被调用,我需要做的是:

this.delegateEvents();

我不知道为什么我必须这样做,因为 backbone 在后台执行此操作:

this.$el.on(eventName, selector, method); 

this.$el 永远不会改变,所以我不知道是什么导致了这个问题。有什么想法吗?

jQuery 的 replaceWith 使用 remove 并在它之前插入内容,来自 jQuery 的删除文档

In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

因此您应该重新绑定视图 el 元素的事件,这是由 delegateEvents 方法完成的。

重新渲染视图时,执行的是:

view.$el.html(Handlebars.compile(view.template)(context));

html 方法从子元素中删除事件处理程序(来自 jQuery 文档)

Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.

这就是为什么我必须重新绑定 elements/events

问题是 this.delegateEvents()Backbone.View 构造函数中只被调用一次,当你渲染它时它运行良好,但在第二次渲染后你会遇到这个问题。

选项:

  1. 在父视图中初始化子视图render()方法
  2. 在子视图中使用 this.delegateEvents() render() 方法