所以我有一个 View ,通过观看窗口上的滚动事件来实现固定的标题。

didInsertElement: function () {
    var self = this;
    $(window).on("scroll resize", function () {
        if (self.onWindowScroll) {
            Ember.run.throttle(self, 'onWindowScroll', 150);
        }
    });
},

onWindowScroll: function () {
    //do stuff
},

willDestroyElement: function () {
    this.set('onWindowScroll', null);
}

这行得通,但我想知道是否有一种更干净的方法来删除附加到滚动事件的逻辑。也许没有更多的事情可以做,因为它的事件发生在窗口本身上,而只是要求互联网专家分享一些智慧:)。

当清理 View 时,摆脱 View 内定义的事件将是一件很整洁的事情。另外,我没有在窗口本身上取消绑定(bind)滚动事件,因为在滚动窗口时可能还有其他组件/ View 需要执行某些操作,而我也不想干涉它们。

最佳答案

是的,您实际上并没有取消订阅该事件,而是在调用该事件时忽略了它。实际上,退订会更好。

didInsertElement: function () {
    var self = this;
    $(window).on("scroll resize", {scope:this}, this.onWindowScroll);
},

onWindowScroll: function (event) {
   Ember.run.throttle(event.data.scope, 'onWindowScrollThrottle', 150);
},

onWindowScrollThrottle: function () {
    //do stuff
},

willDestroyElement: function () {
    $(window).off("scroll resize", this.onWindowScroll);
}

10-04 10:27