gpt4 book ai didi

javascript - 警报多次触发backbonejs窗口

转载 作者:行者123 更新时间:2023-11-30 05:37:49 24 4
gpt4 key购买 nike

我昨天遇到了一件奇怪的事情。我尝试了几次来解决这个问题。当我两次返回相同的页面时,我的应用会多次触发警报,具体取决于我访问该页面的次数。我已经通过这个网站和互联网对这种“僵尸”事物和内存缺失进行了一些研究,但我发现了死胡同。已经 2 天无法解决此问题。

我的代码

查看页面

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);
},

为什么会这样?

最佳答案

调用 View.remove确实会取消委托(delegate) View 设置的事件

remove view.remove()
Removes a view from the DOM, and calls stopListening to remove any bound events that the view has listenTo'd.

但它只能对它知道的事件执行此操作:由事件哈希或调用 this.listenTo

设置的事件

您设置了滚动监听器但从未删除它,这意味着过去的 View 将继续监听:请参阅您的困境演示 http://jsfiddle.net/nikoshr/E6MQ6/

在这种情况下,您不能使用事件的散列,因此您必须自己进行清理,例如通过覆盖 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
}
});

还有一个演示 http://jsfiddle.net/nikoshr/E6MQ6/1/

通过使用命名空间监听器,滚动事件的删除稍微不那么残酷:

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);
}
});

http://jsfiddle.net/nikoshr/E6MQ6/2/

关于javascript - 警报多次触发backbonejs窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22502483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com