我正在构建Backbone应用程序,但遇到了这个奇怪的问题。在状态A(路线:“”)中,我有一个这样的视图:
var view = Backbone.View.extend({
events : {
"click a.continue" : "next"
},
next : function(e) {
//Some stuff
Backbone.history.navigate("/page2");
}
});
并且一旦我用“ continue”类单击锚点,我将被重定向到状态B(路由:“ / page2”)。如果单击浏览器的后退按钮,然后单击锚点,则调试时我注意到next函数被触发两次。实际上,如果我继续来回移动,事件触发的次数将不断增加。
任何线索?
您有一个僵尸视图。
其要点是,当您实例化并显示第二个视图(“状态B”)时,您不会处置第一个视图。如果您有任何事件绑定到视图的HTML或视图的模型,则在关闭表单时需要清除这些事件。
我在此处写了一篇详细的博客文章,http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/
请务必阅读注释,因为“ Johnny O”提供了我认为非常出色的替代实现。
我有同样的问题,解决方法是...
App.Router = Backbone.Router.extend({
routes: {
"fn1": "fn1",
"fn2": "fn2"
},
stopZombies: function(objView){
if(typeof objView === "object"){
objView.undelegateEvents();
$(objView.el).empty();
}
},
fn1: function(){
this.stopZombies(this.lastView);
var view1 = new App.v1();
this.lastView = view1;
},
fn2: function(){
this.stopZombies(this.lastView);
var view2 = new App.v2();
this.lastView = view2;
}
});
将最后一个执行视图存储在this.lastView中,然后stopZoombies()从该视图中删除事件。