javascript - 警报多次触发backbonejs窗口

标签 javascript jquery backbone.js

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

相关文章:

javascript - 在 render 中调用方法或使用 getter

javascript - 我的自动逗号仅适用于第一个文本输入,但不适用于第二个

rest - 什么是最简单、最少的 Backbone.js 代码来做 REST(假设服务器端是正确的)?

javascript - Marionette Controller 功能声明 - 最佳实践

javascript - 帮助找出功能异常的原因

javascript - meteor ;发布后不立即对客户端进行排序

jquery - Javascript - 在隐藏字段中存储对象数组

javascript - 如何检查字符串中的每个数字?

javascript - 难以应用两个不同的脚本

javascript - Rails - 如何向使用 javascript 创建的表单添加 CSRF 保护?