javascript – 重新渲染子视图后,Backbone事件会多次触发
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 重新渲染子视图后,Backbone事件会多次触发,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2348字,纯文字阅读大概需要4分钟。
内容图文
![javascript – 重新渲染子视图后,Backbone事件会多次触发](/upload/InfoBanner/zyjiaocheng/732/204f074f6e6549f09042fb32b43627af.jpg)
我们有一个由侧边栏和几个子视图组成的Backbone视图.为简单起见,我们决定让侧边栏和子视图由单个渲染功能控制.但是,单击其中一个侧边栏项后,单击.edit事件似乎会多次触发.例如,如果我从“general”开始并单击.edit,那么hello会触发一次.如果我然后单击侧栏上的.profile并再次单击.edit,则会两次触发.有任何想法吗?
视图
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});
},
这现在有效,但这会造成内存泄漏吗?
解决方法:
当我第一次开始使用骨干时,我遇到了完全相同的问题.就像Peter说的那样,问题在于你创建了多个View实例并正在监听事件.为解决这个问题,我在上一个骨干项目中创建了这个解决方案:
/* Router view functions */
showContact:function () {
require([
'views/contact'
], $.proxy(function (ContactView) {
this.setCurrentView(ContactView).render();
}, this));
},
showBlog:function () {
require([
'views/blog'
], $.proxy(function (BlogView) {
this.setCurrentView(BlogView).render();
}, this));
},
/* Utility functions */
setCurrentView:function (view) {
if (view != this._currentView) {
if (this._currentView != null && this._currentView.remove != null) {
this._currentView.remove();
}
this._currentView = new view();
}
return this._currentView;
}
正如您所看到的,它总是删除最后一个视图并创建一个新视图然后呈现.我还在路由器中添加了一个require语句,因为我不想在路由器中加载所有视图,直到实际需要它们为止.祝好运.
内容总结
以上是互联网集市为您收集整理的javascript – 重新渲染子视图后,Backbone事件会多次触发全部内容,希望文章能够帮你解决javascript – 重新渲染子视图后,Backbone事件会多次触发所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。