当附加函数具有绑定时移除监听器
Remove Listener when attached Function has Binding
考虑以下代码:
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);
}
一个选项是将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...
}
}
考虑以下代码:
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);
}
一个选项是将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...
}
}