backbone model 重复绑定问题

这是router中的一个函数。
routes:{
"post/:id":"postEdit"
},
postEdit:function(id){
console.log('router.js,gotrouter:#/post/'+id);
UILoading($("#main"));
varmodel=newPostModel({_id:id});
model.fetch({
success:function(){
newPostEditView({model:model});
},
error:function(){
console.log("failed,onrouter:#/post/"+model.id);
}
});
}
接下来是View的代码
varPostEditView=Backbone.View.extend({
el:'#main',
template:doT.template(PostEditTemplate),
events:{
'click#savePost':'save'
},
initialize:function(){
_.bindAll(this,'render');
this.model.bind("change",this.render,this);
varconverter=Markdown.getSanitizingConverter();
this.editor=newMarkdown.Editor(converter);
this.render();
},
render:function(){
this.$el.html(this.template(this.model.toJSON()));
this.editor.run();
},
save:function(){
this.model.set({
title:$("#post_title").val(),
slug:$("#post_slug").val(),
created:$("#post_created").val(),
tags:$("#post_tags").val().split(','),
content:$(".post_content").val()
});
this.model.save();
}
});
最后发现,当访问过多次#/post/5103fbb3817feb1c10000001,/#/post/5103c114ce4c724c12000002后,save这个函数会重复调用。
相当于之前的model没有被释放,事件重复执行了。
如何解决这个问题呢?
GCT1015
浏览 468回答 2
2回答

12345678_0001

自问自答。view的切换,主要由路由来触发,所以在router中加了一个函数来做view切换管理。switchView:function(view){if(this.currentView){this.currentView.remove();}this.currentView=view;},每次route,都调用switchview来进行切换。//#/post/512c4527f7d8797818000001postEdit:function(id){console.log('router.js,gotrouter:#/post/'+id);varthat=this;varmodel=newPostModel({_id:id});varview=newPostEditView({model:model});this.switchView(view);//......dosomething.}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript