Cleaner way to remove events attached to window scope once the view is destroyed

人盡茶涼 提交于 2019-12-12 19:01:13

问题


So I have a view that implements fixed header by watching scroll event on the window.

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

This works but I was wondering if there is a cleaner approach for removing the logic attached to the scroll event. Maybe there is nothing more we can do because its event on window itself, but just asking internet gurus to share some wisdom :).

It would be neat to get rid of events defined within a view when the view gets cleaned up. Also I did not unbind the scroll event on window itself because there might be other components/views which needs to do something when window is scrolled and I don't want to interfere with those.


回答1:


Yeah, you aren't actually unsubscribing from the event, you are just ignoring it when it's called. Actually unsubscribing from it will be better.

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


来源:https://stackoverflow.com/questions/24248977/cleaner-way-to-remove-events-attached-to-window-scope-once-the-view-is-destroyed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!