Deewendra Shrestha
Deewendra Shrestha

Reputation: 2465

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

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.

Upvotes: 2

Views: 520

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

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

Upvotes: 2

Related Questions