【发布时间】: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