I have super-View who is in charge of rendering sub-Views. When I re-render the super-View all the events in the sub-Views are lost.
This is an example:
var SubView = Backbone.View.extend({
events: {
"click": "click"
},
click: function(){
console.log( "click!" );
},
render: function(){
this.$el.html( "click me" );
return this;
}
});
var Composer = Backbone.View.extend({
initialize: function(){
this.subView = new SubView();
},
render: function(){
this.$el.html( this.subView.render().el );
}
});
var composer = new Composer({el: $('#composer')});
composer.render();
When I click in the click me div the event is triggered. If I execute composer.render() again everything looks pretty the same but the click event is not triggered any more.
Check the working jsFiddle.
When you do this:
You’re effectively saying this:
and
emptykills the events on everything insidethis.$el:So you lose the
delegatecall that binds events onthis.subViewand theSubView#renderwon’t rebind them.You need to slip a
this.subView.delegateEvents()call intothis.$el.html()but you need it to happen after theempty(). You could do it like this:Demo: http://jsfiddle.net/ambiguous/57maA/1/
Or like this:
Demo: http://jsfiddle.net/ambiguous/4qrRa/
Or you could
removeand re-create thethis.subViewwhen rendering and sidestep the problem that way (but this might cause other problems…).