【发布时间】:2013-07-23 23:08:47
【问题描述】:
我们有一个由侧边栏和几个子视图组成的 Backbone 视图。为简单起见,我们决定让侧边栏和子视图由单个 render 函数管理。然而,click .edit 事件似乎在单击侧边栏项目之一后触发了多次。例如,如果我从“常规”开始并单击.edit,则hello 会触发一次。如果我然后单击侧边栏上的.profile 并再次单击.edit,hello 会触发两次。有什么想法吗?
查看
events: {
"click .general": "general",
"click .profile": "profile",
"click .edit": "hello",
},
general: function() {
app.router.navigate("/account/general", {trigger: true});
},
profile: function() {
app.router.navigate("/account/profile", {trigger: true});
},
render: function(section) {
$(this.el).html(getHTML("#account-template", {}));
this.$("#sidebar").html(getHTML("#account-sidebar-template", {}));
this.$("#sidebar div").removeClass("active");
switch (this.options.section) {
case "profile":
this.$("#sidebar .profile").addClass("active");
this.$("#content").html(getHTML("#account-profile-template"));
break;
default:
this.$("#sidebar .general").addClass("active");
this.$("#content").html(getHTML("#account-general-template"));
}
},
hello: function() {
console.log("Hello world.");
},
路由器
account: function(section) {
if (section) {
var section = section.toLowerCase();
}
app.view = new AccountView({model: app.user, section: section});
},
解决方案
我的解决办法是把路由器改成这样:
account: function(section) {
if (section) {
var section = section.toLowerCase();
}
if (app.view) {
app.view.undelegateEvents();
}
app.view = new AccountView({model: app.user, section: section});
},
这暂时可行,但这会造成内存泄漏吗?
【问题讨论】:
-
如果您发布您的路由器代码,我可以验证您正在创建重复视图实例的预感。
-
好的,我把路由器的相关部分贴出来了。