删除视图后,删除窗口范围事件的更干净方法 [英] Cleaner way to remove events attached to window scope once the view is destroyed

查看:70
本文介绍了删除视图后,删除窗口范围事件的更干净方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个视图,通过观看窗口上的滚动事件来实现固定标头。

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.

推荐答案

是的,您实际上并没有取消订阅该事件,只是在调用该事件时忽略了该事件。

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

这篇关于删除视图后,删除窗口范围事件的更干净方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆