我有一个名为 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) 在 WidgetView
的 render
方法中,用它的模型填充 @el
( View 的根元素)通过模板的数据。 (请注意我是如何只编译模板一次的——不需要在每次渲染操作时都编译模板。)
(2) 在 DashboardView
中,您将小部件的根元素 - @el
- 附加到 DOM。
问题是 View 的事件委托(delegate)给它的根元素 - @el
。因此,您想显式地使用根元素:在 render
中填充它,然后将它附加到 DOM。
关于javascript - Backbone.js 嵌套 View 中的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9550055/