var UserView = Backbone.View.extend({
initialize: function(){
MData.blankHeader.data.topBar.title = '<h1 id="titleLogo">' + this.options.userName + '</h1>';
MData.blankHeader.data.topBar.btn1 = '';
MData.blankHeader.data.topBar.btn2 = '<a href="#" id="sendDm" class="cu-round-btn">???</a>';
$('header').html(Mustache.to_html($('#headerTpl').html(), MData.blankHeader)).append('<div class="topbar-shadow"></div>');
$('footer').html(Mustache.to_html($('#footerTpl').html(), MData.eventlistFooter)).attr('id','').find('.selected').removeClass('selected').end().find('.footer-item:eq(3)').addClass('selected');
$('#content').css({"top": $('header').height() + 'px'});
setTimeout(function(){
scrollinit();
},0);
onScrollEnd = true;//??
this.render();
},
events:{
"click #sendDm" : "sendDm"
},
el: $('body'),
sendDm: function(e){
alert('send dm');
e.preventDefault();
},
render: function(){
var html = "";
html += Mustache.to_html($("#userTpl").html(), this.options.userData);
$('#pullDown').css("display","none");
$('#ajaxEvent').html(html);
console.log(this.options.userId);
if(this.options.userName != "me"){
$('#dm').remove();
}
calTime();
function calTime(){
_.each($('.user-timeStamp'), function(date){
$(date).html(humaneDate(date.innerHTML));
});
}
setInterval(calTime,60000)
return this;
}
});
//code in Router
var newUser = new UserCol();//new a Collection
newUser.fetch({
data: param,
success: function(model,data){
new UserView({userData: data, userId: param})
}
})
Run Code Online (Sandbox Code Playgroud)
因此,当我多次查看此页面(更改地址栏中的参数)时,主干将多次新建UserView,并且事件绑定到按钮将多次触发,如何才能使按钮触发一次.
你有内存泄漏和僵尸视图对象
events在骨干视图中的范围限定el为指定(或为您生成).因为你已经指定了elas body,所以click #sendDm事件将找到id为的元素的任何实例sendDm.
当您更改网址中的路由时,路由器正在接收更改并加载视图...但旧视图永远不会被正确关闭或删除,因此您将留下一个挂在内存中的僵尸视图对象,绑定到#sendDm元素的click事件.每次你移动到一个新的路线并加载另一个视图时,你将留下另一个僵尸形式,绑定到该元素.
不要指定body为你的el.另外 - 不要this.render()从您的视图的初始化方法调用.相反,让你的路由器处理知识body并让它渲染视图,同时删除旧视图:
var newUser = new UserCol();//new a Collection
MyRouter = Backbone.Router.extend({
routes: {"some/route/:id": "showIt"},
initialize: function(){
_.bindAll(this, "showUser");
}
showIt: function(id){
newUser.fetch({
data: param,
success: this.showUser
});
},
showUser: function(model,data){
if (this.userView){
this.userView.unbind();
this.userView.remove();
}
var view = new UserView({userData: data, userId: param});
view.render();
$('body').html(view.el);
this.userView = view;
}
});
Run Code Online (Sandbox Code Playgroud)