Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 页面刷新绑定主干事件两次_Javascript_Jquery_Backbone.js - Fatal编程技术网

Javascript 页面刷新绑定主干事件两次

Javascript 页面刷新绑定主干事件两次,javascript,jquery,backbone.js,Javascript,Jquery,Backbone.js,我使用主干网创建了一个广泛的应用程序。到目前为止,一切都很顺利。但是,当我刷新/重新加载给定散列(例如myapp/#dashboard)上的页面时,视图会呈现两次,所有事件都会绑定两次。如果我去另一个区回来。一切正常 我使用的子程序如下所示: var DashboardRouter = Backbone.SubRoute.extend({ routes : { /* matches http://yourserver.org/books */ "" : "

我使用主干网创建了一个广泛的应用程序。到目前为止,一切都很顺利。但是,当我刷新/重新加载给定散列(例如myapp/#dashboard)上的页面时,视图会呈现两次,所有事件都会绑定两次。如果我去另一个区回来。一切正常

我使用的子程序如下所示:

var DashboardRouter = Backbone.SubRoute.extend({
    routes : {
        /* matches http://yourserver.org/books */
        "" : "show",
    },

    authorized : function() {
        // CODE TO RETRIEVE CURRENT USER ID ...
        return (lg);
    },

    show : function() {
        var usr = this.authorized();
        if (this.dashboardView) {
            this.dashboardView.undelegateEvents();
        }
        switch(usr) {
            case 2:
                this.dashboardView = new StudentDashboard();
                break;
            case 3:
                this.dashboardView = new CounsellorDashboard();
                break;
            case 4:
                this.dashboardView = new AdminDashboard();
                break;
            default:
                location.replace('#signout');
        }
    },
});
我在控制台中进行了检查,这里的事件只调用一次。学生仪表板如下所示(摘录)


从控制台日志中,我知道所有子视图通常只渲染一次,但在刷新页面时渲染两次,我不知道原因。

在重新渲染之前,您需要确保视图上的所有事件都未连接

在视图中添加以下函数

cleanup: function() {
    this.undelegateEvents();
    $(this.el).empty();
}
现在,在渲染视图之前,在路由器中,如果视图已经存在,请执行清理

if (this.myView) { this.myView.cleanup() };
this.myView = new views.myView();

不确定这是否是一个问题,但
model:new Student()
是一件奇怪的事情,它将一个
new Student
放在
仪表板视图
原型中,这样所有视图实例都将共享同一个模型实例。您可能希望在视图的
initialize
中使用
this.model=new Student
if (this.myView) { this.myView.cleanup() };
this.myView = new views.myView();