Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove event listeners in Aurelia?

Tags:

aurelia

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.

like image 952
chovy Avatar asked Feb 09 '23 20:02

chovy


1 Answers

There is at least one, but maybe two issues here.

Setting up an event listener

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);
}

How to write a lifecycle callback

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);
}
like image 119
Matthew James Davis Avatar answered Mar 07 '23 18:03

Matthew James Davis