当附加函数具有绑定时删除监听器

时间:2019-06-02 23:30:19

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

考虑以下代码:

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

1 个答案:

答案 0 :(得分: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...
    }
}