I have a view called DashboardView that instantiates multiple WidgetViews. Each widget needs to have its own event bindings. So far as I can tell, these bindings get lost when the view is rendered and added to the parent view, i.e.:
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)
Doing it this way, the click events on the .config element of the widget are now lost. Is there a better way of mixing the nested views into the parent while ensuring that the event handlers on the child view are channelled correctly?
One solution I have seen to this problem comes in this article. This looks about right, but I’m curious if there is a more elegant way of solving this.
Try this:
So, the idea is this:
(1) Inside the
WidgetView‘srendermethod, you populate@el(the root element of the view) with its model’s data via the template. (And notice how I compile the template only once – there is no need to compile the template on each render operation.)(2) Inside the
DashboardView, you append the widget’s root element –@el– to the DOM.The thing is that the view’s events delegate to its root element –
@el. Therefore, you want to work with the root element explicitly: insiderender, you populate it, and then you append it to the DOM.