使用$element.html(anotherView)
将视图替换为其他内容后,视图中设置的事件不会触发,然后使用#element.html(theView)
将其放回页面。
示例:
var BuggyView = Backbone.View.extend({
// Event works the at first, but not after the view is replaced, then added back
// onto the page
events:{
'click #some-element': 'on_click_some_element'
},
// This function gets called before the view is replaced by another view, but
// not after it is added back into the page the second time
on_click_some_element:function(event){
alert('User clicked "some element"');
}
});
此代码执行后事件有效:
// Create the new view:
var buggyView = new BuggyView({});
// Add the view to the page
$element.html(buggyView.el);
此代码将在以后用其他内容替换页面上的视图时发生:
$element.html(anotherView.el);
将视图添加回页面后,事件不再起作用:
$element.html(buggyView.el);
答案 0 :(得分:1)
在DOM中设置视图元素后运行render:
$element.html(anotherView.el);
anotherView.render();
$element.html(theView.el);
theView.render();
可能你的问题是渲染没有再次运行。您只是切换DOM分配。
答案 1 :(得分:1)
最有可能在删除视图时,您也删除了视图的绑定事件,您可能需要redelgate your events。或者不使用(jquery)。remove使用.detach。