I need to remove the wheel eventlistener immediately after it fired. I tried the following but its not removing the eventlistener.
export class HomeComponent implements OnInit {
constructor() {}
ngOnInit() {
document.querySelector("#section-one").addEventListener("wheel", () => this.myFunction1(), true);
}
myFunction1() {
alert();
document.querySelector("#section-one").removeEventListener("wheel", this.myFunction1, true);
console.log("Done!");
}
}
Any suggestions?
Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.
TLDR; Always remove event listeners when you don't plan on using them any longer.
Removing the event listener first always results in lower memory usage (no leaks).
According to the docs:
Calling removeEventListener() with arguments that do not identify any currently registered EventListener on the EventTarget has no effect.
your code shouldn't work.
Possible fix can be as follows:
wheelHandler: any;
ngOnInit() {
this.wheelHandler = this.myFunction1.bind(this);
document.querySelector("#section-one").addEventListener("wheel", this.wheelHandler, true);
}
myFunction1() {
alert();
document.querySelector("#section-one").removeEventListener("wheel", this.wheelHandler, true);
console.log("Done!");
}
where wheelHandler
is a function referring to the same instance of handler
For more angular way solution see
But AFAIK useCapture
parameter is not supported yet. So it's always false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With