InnerView 未响应其模板中的 DOM 事件

InnerView not responding to DOM events in its template

问题:当我在另一个视图的范围内创建 Backbone 视图时,内部视图没有响应源自其模板内部的 DOM 事件,但是外部视图正在响应到那些事件。在下面的示例中,innerview 有一个提交按钮,但只有 outerview 会响应 submitButton

的点击

我正在制作一个 Backbone 项目,该项目为路由器中的每个路由创建一个新的主视图,并且该主视图可能具有其页面不同部分的子视图。例如,有一个创建 OrderView 页面的 order 路由

routes: {

            'order': 'orderProduct'
        },

orderProduct: function(){

            this.loadView(new OrderView()); 

        },

在OrderView的初始化函数中,我为OrderView创建了子视图,例如一个formView。

 var OrderView = Backbone.View.extend({


        initialize: function(){
            $("body").html(this.el);
            this.template = _.template($('#order-template').html()),

            this.subViews = [];
            var formView = new FormView();
            this.subViews.push(formView);
            this.render();
        }, 

然后在 FormView 中,我创建了一个显而易见的东西,例如 submitButton

 var FormView = Backbone.View.extend({
        el: '#forForm',

        initialize: function(){
            this.template = _.template($('#form-template').html());
        },
        events: {
            'click #submitButton' : 'submitForm',
            },

        submitForm: function(){
            ...
        },

        render: function(){

            $('#forForm').append(this.template());
            return this;

        } 
     });

表单已呈现到页面,但当我单击“提交”时,没有任何反应。然后,我向 OrderView 添加了事件处理程序和相应的函数 'click #submitButton' : 'submitForm',,它响应了提交事件。所以我的问题是,当我在 OrderView 范围内创建 FormView 时,为什么 FormView 不能响应其模板范围内的事件?

表单模板

   <script type="text/template" id="form-template">
    <button id="submitButton">submit</button>
   </script>

更新:

我应该注意到附加表单模板(由内部视图呈现)的 dom 元素包含在订单模板(外部视图)中。即使是这种情况,由于 FormView 响应的事件源自表单模板内的点击(即单击 submitButton 时),我假设 FormView 能够响应事件。

<script type="text/template" id="order-template">
  <div class="container">

    <div class='row'>

      <div class="col-md-6">



     <div id="forForm">
     </div>



      </div> 
      <div class="col-md-6">

     ...ommitted...

      </div> 

  </div>

  </div>

</script>

我不确定我是否完全理解这个问题,但我会尝试通过解释一些逻辑来回答这个问题。

Backbone 依赖 jquery on 注册到由 DOM.
触发的事件 这意味着当您实例化一个 Backbone 视图并定义其 events: {} 对象时,您的视图将能够侦听这些事件,并将视图的 el 作为事件所在的父元素所有子元素都会冒泡。

如果父视图定义了一个 el 来包装子视图上定义的 el's,那么从逻辑上讲,这些事件将冒泡到最高父视图。
如果父视图也决定在与内部视图相同的子元素上监听点击事件,那么这个事件会冒泡到最高的父元素,除非你决定结束从子视图的传播,你可以通过从处理子视图中事件的方法调用 $(event.currentTarget).stopPropagation()

我希望这对您有所帮助,并能帮助您解决问题。

出于某种原因,在从 OrderView 的渲染函数渲染 FormView 时,我不得不使用 setElement,将 OrderView 容器设置为 FormView 的元素。我不知道为什么这是必要的。我见过许多 Backbone 应用程序在一个视图中呈现另一个视图(例如,应用程序为 ul 和列表中的每个 li 使用单独的视图),这似乎从来没有必要

这是OrderView渲染函数的相关代码

        _.each(this.subViews, function(view) {          
            view.setElement( this.$el.find('.orderview-container') ).render().el;           
        }, this);