我们有一个单独的骨干视图,由一个侧栏和几个子视图组成。为了简单起见,我们决定使用单个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});
},
这适用于现在,但会造成内存泄漏吗?
如果你发布你的路由器代码,我可以验证我的直觉,你正在创建重复的视图实例。 –
好的,我发布了路由器的相关部分。 –