javascript - Backbone.js 嵌套 View 中的事件

标签 javascript backbone.js coffeescript backbone-events

我有一个名为 DashboardView 的 View ,它实例化了多个 WidgetView。每个小部件都需要有自己的事件绑定(bind)。据我所知,当 View 被渲染并添加到父 View 时,这些绑定(bind)会丢失,即:

class DashboardView extends Backbone.View
  constructor: -> 
    context = @
    _.each @collection, (w)->
      dv = new app.WidgetView(model: w)
      context.$el.append(dv.render()) 

class WidgetView extends Backbone.View
  events: 
     "click .config" : "config_widget"

  render: ->
      _.template($("#widget-template").html(), @model)

通过这种方式,小部件的 .config 元素上的点击事件现在丢失了。有没有更好的方法将嵌套 View 混合到父 View 中,同时确保正确引导 subview 上的事件处理程序?

我看到这个问题的一个解决方案是 this article .这看起来是正确的,但我很好奇是否有更优雅的方法来解决这个问题。

最佳答案

试试这个:

class DashboardView extends Backbone.View
  constructor: -> 
    @collection.each ( w ) =>
      dv = new app.WidgetView( model: w )
      @$el.append dv.render().el // Append widget's @el explicitly

class WidgetView extends Backbone.View
  tagName: 'div' // or whatever your view's root element is

  template: _.template $( "#widget-template" ).html() // pre-compile template

  events: 
    "click .config": "config_widget"

  render: ->
    @$el.html @template @model.toJSON() // append template to @el
    return this // return view

所以,想法是这样的:

(1) 在 WidgetViewrender 方法中,用它的模型填充 @el( View 的根元素)通过模板的数据。 (请注意我是如何只编译模板一次的——不需要在每次渲染操作时都编译模板。)

(2) 在 DashboardView 中,您将小部件的根元素 - @el - 附加到 DOM。

问题是 View 的事件委托(delegate)给它的根元素 - @el。因此,您想显式地使用根元素:在 render 中填充它,然后将它附加到 DOM。

关于javascript - Backbone.js 嵌套 View 中的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9550055/

相关文章:

php - 重用服务器端的主干应用程序以在服务器端渲染 View

javascript - 有没有办法在 Rails 4 的 Coffeescript/Javascript 中使用 ActionView Helpers?

javascript - Meteor JS Autoform 自定义输入 - 没有当前 View

javascript:如果日期在 1 月 15 日之后,则设置隐藏字段

javascript - 有没有 window.showModalDialog 和 window.open 的替代方案

javascript - KnockoutJS - 计算的可写可观察对象无法正确更新绑定(bind)

javascript - Backbone 动态创建 'el' 未绑定(bind)事件

javascript - 如何在 html/javascript 中使用 dom 检索图像的大小?

javascript - 在主干路由中包含根

javascript - 我可以使用新的 'controller as' 语法将 Typescript 类用作 AngularJS Controller 吗