I have broken down this issue into the smallest example possible (i.e., it's only to demonstrate the problem, not to necessarily represent a real-world scenario).
Let's say I have a parent view ("MainView" here) that contains a child view ("SubView" here). If, at any point, I need to re-render the parent view (which thereby re-renders the child view), I am losing the event bindings in the child view, despite calling delegateEvents
.
A jsfiddle can be found here: http://jsfiddle.net/ya87u/1/
Here is the code in full:
var MainView = Backbone.View.extend({
tagName : "div",
initialize : function() {
this.subView = new SubView();
},
render : function() {
this.$el.html(this.subView.render().$el); // .html() breaks binds
this.subView.delegateEvents(); // this re-establishes them
return this;
}
});
var SubView = Backbone.View.extend({
tagName : "div",
events : {
"click .button1" : "onButtonPress"
},
onButtonPress : function() {
alert("Button pressed");
},
render : function() {
var html = "<button class='button1'>Button1</button>";
this.$el.html(html);
return this;
}
});
var v = new MainView();
$("#area1").html(v.render().$el); // binds work fine
// do some work... then re-render...
$("#area1").html(v.render().$el); // breaks event binds
I do not understand why this is happening. Any input would be greatly appreciated.