Skip to main content Accessibility Feedback

Why do you store event handlers as instance properties in a Web Component?

Last week, I shared an example of a Web Component that’s part of my Web Component collection on the Lean Web Club.

In it, I have a createHandler() function that creates an event handler callback, which I store as an instance property (this.handler) when the Web Component is instantiated.

constructor () {
	super();
	this.handler = this.createHandler();
}

createHandler () {
	return (event) => {
		// Do event handler stuff...
	};
}

connectedCallback () {
	this.addEventListener('input', this.handler);
}

In my Discord, someone asked me why I do that instead of just doing this…

connectedCallback() {
	this.addEventListener('input', (event) => {
		// Do event handler stuff...
	});
}

Great question!

With Web Components, it’s a good practice to remove event listeners when the custom element is removed from the DOM. This helps reduce load on the browser’s memory for event listeners that are no longer needed.

We can do that in the disconnectedCallback() method.

disconnectedCallback () {
	this.removeEventListener('input', this.handler);
}

But in order to remove a listener with the removeEventListener() method, you need to pass in the same exact arguments that you used to create the event listener, including the same function.

To do that, we need a named reference for our function that we can point to. That’s why I save it as a property (this.handler). If I passed in an anonymous function, the handler wouldn’t be removed.

// This WON'T remove the listener
disconnectedCallback() {
	this.removeEventListener('input', (event) => {
		// Do event handler stuff...
	});
}

I don’t actually need the createHandler() function. I could create the handler function directly inside the constructor() method.

constructor () {
	super();
	this.handler = (event) => {
		// Do handler stuff...
	};
}

But for handler functions that do more than one line of code, I think moving it all to its own function makes things easier to read and maintain.