Here is a code snippet to consider:
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...
}
}
The code above shows that an event listener is attached in the add
method, and then attempted to be removed in the remove
method. The bind(this)
part in the breakpoint
method appears to be essential for its functionality.
It seems that due to the bind(this)
, the removeListener
is not successfully removing the media query listener. Are there any solutions to address this issue?
I also tried the following (without using bind
on remove):
remove(options) {
this.breakpoints[options.breakpoint].removeListener(this.breakpoint);
}