chovy
chovy

Reputation: 75666

How to remove event listeners in 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.

Upvotes: 4

Views: 2095

Answers (2)

Matthew James Davis
Matthew James Davis

Reputation: 12295

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

Upvotes: 5

Soft Bullets
Soft Bullets

Reputation: 5095

It's worth noting that you need to define your bindable function up in the constructor if you want to unbind it again on detach:

export MyClass {

constructor() {

    this.handleBodyClick = e => {

        console.log(e.target);
    };
}

attached() {

    document.addEventListener('click', this.handleBodyClick);
}

detached() {

    document.removeEventListener('click', this.handleBodyClick);
}   

Taken directly from this excellent post: http://ilikekillnerds.com/2016/02/using-event-listeners-in-aurelia/

Upvotes: 3

Related Questions