How to remove event listeners in Aurelia?
This doesn’t appear to do anything:
detached(){
window.removeEventListener('scroll', this.windowScroll);
}
The event is still firing when i change routes.
I am attaching it in the constructor()
in my view-model file:
window.addEventListener('scroll', this.windowScroll.bind(this));
I also tried deactivate()
and neither are firing when I change routes.
There is at least one, but maybe two issues here.
If you can't use the Aurelia binding for event delegation (for which scroll may or may not be a case, I haven't tried it), then you should use the attached lifecycle callback to set up your event handlers, not the constructor. The reason being that, unless you specify your view model is transient, the constructor will be called once. Instead, you really want Aurelia to turn on your event handlers every time it is attached.
attached = () => {
window.addEventListener('scroll', this.onScroll);
}
In general you should write your lifecycle callbacks using the arrow notation. This is because, IIRC, your this
may get reassigned during the activation lifecycle. The arrow notation in TypeScript/ES6 will preserve your this
lexically, i.e., it is what you expect it to be.
detached = () => {
window.removeEventListener('scroll', this.onScroll);
}
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