【问题标题】:Remove Listener when attached Function has Binding附加函数具有绑定时删除侦听器
【发布时间】:2019-10-18 13:23:05
【问题描述】:

考虑以下代码:

class Test {

    constructor() {
        this.breakpoints = {};
    }

    add(options) {

        // Register the media query
        this.breakpoints[options.breakpoint] = window.matchMedia(options.breakpoint);

        // Register the listener
        this.breakpoints[options.breakpoint].addListener(this.breakpoint.bind(this));

    }

    remove(options) {
        this.breakpoints[options.breakpoint].removeListener(this.breakpoint.bind(this));
    }

    breakpoint() {
        // Do something...
    }
}

在上面的代码中,您会注意到我在add 方法中附加了一个事件侦听器,并试图在remove 方法中删除它。由于breakpoint 方法中的代码,bind(this) 部分绝对至关重要。

由于bind(this)(我相信),removeListener 不会删除媒体查询侦听器。有没有办法解决这个问题?

我也试过这个(删除时没有bind):

remove(options) {
    this.breakpoints[options.breakpoint].removeListener(this.breakpoint);
}

【问题讨论】:

  • 构造函数中this.breakpoint = this.breakpoint.bind(this);的替代方法是将函数定义为箭头函数:class Test { breakpoint = () => {...} }

标签: javascript ecmascript-6 ecmascript-5 ecmascript-2017


【解决方案1】:

一种选择是在构造函数中将breakpoint方法绑定到当前实例的上下文,这样以后引用this.breakpoint总是引用绑定的方法:

class Test {
    constructor() {
        this.breakpoint = this.breakpoint.bind(this);
        this.breakpoints = {};
    }

    add(options) {
        // Register the media query
        this.breakpoints[options.breakpoint] = window.matchMedia(options.breakpoint);

        // Register the listener
        this.breakpoints[options.breakpoint].addListener(this.breakpoint);
    }

    remove(options) {
        this.breakpoints[options.breakpoint].removeListener(this.breakpoint);
    }

    breakpoint() {
        // Do something...
    }
}

【讨论】:

  • 不完全确定您是如何如此迅速地回答这个问题的……经过测试并且有效!我永远也想不通!非常感谢,非常感谢您的帮助!一旦我能够接受答案,我会接受
猜你喜欢
  • 2018-04-26
  • 2019-01-26
  • 2015-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多