Removing listener for custom event

To allow Aurelia to interoperate with other components on the page, I want to use a custom event, so I add this to my ViewModel’s activate method:
document.addEventListener(‘my-custom-event’, event => {
this.eventHandler(event.detail);
}, false);
This works fine, however I cannot see a way to handle this in the deativate method where I want to remove the event listener as removeEventListener needs a function name and I must use the fat arrow syntax to bind the local scope, but then the function is anonymous.

Any help would be appreciated.

R

1 Like

This should work!

export class MyComponent
{
	onEvent = event => {
		this.eventHandler(event.detail);
    }
	
	attached() {
		document.addEventListener('my-custom-event', this.onEvent);
	}
	
	detached() {
		document.removeEventListener('my-custom-event', this.onEvent);
	}
}
1 Like

@elitastic gave a correct answer.

You should note that functions are values in JavaScript as well. (They are instances of the Function class.) If you tried to pass anonymous functions to addEventListener and removeEventListener, JavaScript would handle those two anonymous functions as two independent values, even if they have the same signature and body. So that does not work as expected.

So you are right that you need to name your function. (Or assign it to a variable, which is effectively the same.)

@elitastic introduced a class member called onEvent in his answer, which refers to the desired event listener function to use. By using that single onEvent variable in both the addEventListener and removeEventListener calls, it will work as expected.

As you can see, it is quite fine to assign arrow functions to variables as well. @elitastic’s solution might even work with a regular function, but then you will need to explicitly bind that function to the class instance for the this keyword to work correctly. Something like this:

onEvent = (function (this, event) {
  this.eventHandler(event.detail);
}).bind(this);

Personally, I prefer arrow functions here.

1 Like

Thanks @elitastic and @Bart. This proves I still have plenty to learn.

R

1 Like

For the sake of completeness, you can add this as an event handler which implements handleEvent function. With many handles it’ll save you a couple memory bytes :slight_smile:

2 Likes