0
我已經使用Backbone創建了一個廣泛的應用程序。到目前爲止,一切運作良好。但是,當我刷新/重新加載給定哈希上的頁面(例如myapp /#dashboard)時,視圖會呈現兩次,並且所有事件都會綁定兩次。如果我去另一節回來。一切正常。頁面刷新將骨幹事件綁定兩次
我使用subrouter,看起來像這樣:
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');
}
},
});
我已經在控制檯中檢查,這裏的事件稱爲一次。學生儀表板看起來像這樣(摘錄)
DashboardView = Backbone.View.extend({
el : "#maincontent",
template : tpl,
model : new Student(),
events : {
"click #edit-dashboard" : "editDashboard",
"click #add-grade" : "addGrade",
"click #add-test" : "addTest",
"click #add-eca" : "addECA"
},
initialize : function() {
// BIND EVENTS
_.bindAll(this, 'render', 'editDashboard', 'renderGrades', 'renderTests', 'renderECAs', 'renderPreferences');
this.model.on("change", this.render);
this.model.id = null;
this.model.fetch({
success : this.render
});
},
render : function() {
$(this.el).html(this.template(this.model.toJSON()));
// set location variables after main template is loaded on DOM
...
if (!this.gradeList) { this.renderGrades(); };
if (!this.testList) { this.renderTests(); };
if (!this.ecaList) { this.renderECAs(); };
if (!this.preferencesView) { this.renderPreferences(); };
this.delegateEvents();
return this;
},
從控制檯日誌我知道,所有的子視圖通常只渲染一次,而是兩次,當我刷新頁面,我不知道爲什麼。
不知道這是一個問題,但'模型:新學生()'是一個奇怪的事情,這使單一的'新Student'在'DashboardView'原型,以相同的模型實例會由所有視圖實例共享。您可能需要在您的視圖的'initialize'中使用'this.model = new Student'。 –