为了账号安全,请及时绑定邮箱和手机立即绑定

backbone model 重复绑定问题

backbone model 重复绑定问题

GCT1015 2019-04-07 09:38:06
这是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没有被释放,事件重复执行了。如何解决这个问题呢?
查看完整描述

2 回答

?
12345678_0001

TA贡献1802条经验 获得超5个赞

自问自答。
view的切换,主要由路由来触发,所以在router中加了一个函数来做view切换管理。
switchView:function(view){
if(this.currentView){
this.currentView.remove();
}
this.currentView=view;
},
每次route,都调用switchview来进行切换。
//#/post/512c4527f7d8797818000001
postEdit:function(id){
console.log('router.js,gotrouter:#/post/'+id);
varthat=this;
varmodel=newPostModel({_id:id});
varview=newPostEditView({model:model});
this.switchView(view);
//......dosomething.
}
                            
查看完整回答
反对 回复 2019-04-07
  • 2 回答
  • 0 关注
  • 467 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号