How can I remove event listeners in Aurelia?

How do I remove event listeners in Aurelia?

This does nothing:

detached(){
  window.removeEventListener('scroll', this.windowScroll);
}

      

The event still fires when routes are changed.

I am attaching it in constructor()

in my model model file:

window.addEventListener('scroll', this.windowScroll.bind(this));

      

I also tried deactivate()

and didn't shoot when changing routes.

+3


source to share


2 answers


There is at least one, but possibly two questions here.

Setting up an event listener

If you cannot use the Aurelia binding for event delegation (for which there may or may not be scrolling, I have not tried it) then you should use the associated lifecycle callback to set up your event handlers, not the constructor. The reason is that if you don't specify that your viewmodel is temporary, the constructor will be called once . Instead, you really want Aurelia to include 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 lifecycle callbacks using arrow notation. This is because IIRC, yours this

can be reassigned during the activation lifecycle. Arrow notation in TypeScript / ES6 will preserve your this

lexically, i.e. This is what you expect from him.

detached = () => { 
    window.removeEventListener('scroll', this.onScroll);
}

      

+2


source


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

export MyClass {

constructor() {

    this.handleBodyClick = e => {

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

attached() {

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

detached() {

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

      



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

+2


source







All Articles