考虑以下代码:
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);
}
答案 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...
}
}