Javascript backbonejs窗口多次触发警报
我昨天收到一件奇怪的东西。我花了好几次时间来解决这个问题。当我两次返回同一页面时,我的应用程序会多次触发警报,这取决于我访问该页面的次数。我已经通过这个网站和互联网做了一些关于“僵尸”和内存不足的研究,但我发现了死胡同。已经2天了,无法解决此问题Javascript backbonejs窗口多次触发警报,javascript,jquery,backbone.js,Javascript,Jquery,Backbone.js,我昨天收到一件奇怪的东西。我花了好几次时间来解决这个问题。当我两次返回同一页面时,我的应用程序会多次触发警报,这取决于我访问该页面的次数。我已经通过这个网站和互联网做了一些关于“僵尸”和内存不足的研究,但我发现了死胡同。已经2天了,无法解决此问题 我的代码 查看页面 initialize: function() { $(window).scroll(function() { if ($(window).scrollTop() + $(window).heigh
initialize: function() {
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() == $(document).height()) {
alert("bottom!");
}
});
this.bind("reset", this.updateView());
},
render: function() {
this.$el.html(notificationListViewTemplate);
},
updateView: function() {
console.log("clear");
this.remove();
this.render();
}
路由器
showNotificationList: function(actions) {
var notificationListView = new NotificationListView();
this.changePage(notificationListView);
},
为什么会发生这种情况?调用确实会取消对视图设置的事件的委派
删除查看.删除()从DOM中删除视图,并调用stopListening以删除该视图已侦听的所有绑定事件 但它只能对它知道的事件执行此操作:由事件哈希或调用
this.listenTo设置的事件
您设置了一个滚动侦听器,但从未删除它,这意味着过去的视图将继续侦听:请参阅此演示
在这种情况下,您不能使用事件哈希,因此必须自己清理,例如通过覆盖remove
方法:
var V = Backbone.View.extend({
initialize: function() {
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() == $(document).height()) {
console.log("bottom!");
}
});
},
render: function() {
},
updateView: function() {
console.log("clear");
this.remove();
this.render();
},
remove: function() {
Backbone.View.prototype.remove.call(this);
$(window).off('scroll'); // for example, will remove all listeners of the scroll event
}
});
还有一个演示
通过使用名称空间的侦听器,稍微不太残酷地删除scroll事件:
var V = Backbone.View.extend({
initialize: function() {
$(window).on('scroll.'+this.cid, function() {
...
});
},
remove: function() {
Backbone.View.prototype.remove.call(this);
$(window).off('scroll.'+this.cid);
}
});
另一种不太残酷的可能性是使用带有$(窗口)的命名方法。打开('scroll',this.pancakes)
,这样您就可以$(窗口)。关闭('scroll',this.pancakes)
。