Sub topic 8
Adding a listener with addEventListener
This chapter assumes you can already create and dispatch a CustomEvent from a child component and handle it in a parent template with an on attribute such as onproductselected={handleProductSelected}. It also assumes you know the LWC lifecycle hooks connectedCallback, renderedCallback, and disconnectedCallback.
When the template is not enough
In most cases the template attribute is the right way to listen. It is declarative, LWC attaches and removes the listener for you, and it works when the child is rendered conditionally. If the child sits inside lwc:if, the listener attaches when the child renders.
Some situations need a listener you add yourself in JavaScript:
- One listener should serve many children, for example every tile inside a list.
- You want to listen on the component's own template for events that bubble up from any depth.
- The listener must be added or removed at a specific moment, such as in response to another event.
- You need
addEventListeneroptions such asonce. - You need to listen to something that is not a child element in your template, such as
windowordocument.
The mechanism is the standard DOM method addEventListener(type, listener). In LWC, the object you call it on decides which events you receive.
| Call it on | Receives |
|---|---|
| `this.template` | Events from elements in the component's own template that bubble up to the template root |
| A child element from `this.template.querySelector(...)` | Events dispatched by that child, bubbling or not |
| `this` | Events dispatched on the component's host element |
Listening on this.template
A listener on this.template catches every event of that type that bubbles up from the elements in your template. The child must therefore set bubbles: true. Without it, the event never reaches the template root. This is the most common mistake with this technique.
The child dispatches a bubbling event:
// productTile.js
import { LightningElement, api } from 'lwc';
export default class ProductTile extends LightningElement {
@api productId;
@api name;
handleClick() {
this.dispatchEvent(
new CustomEvent('productselected', {
detail: { productId: this.productId },
bubbles: true
})
);
}
}<!-- productTile.html -->
<template>
<button onclick={handleClick}>{name}</button>
</template>The parent template has no onproductselected attribute on either tile:
<!-- productList.html -->
<template>
<c-product-tile product-id="p1" name="Desk"></c-product-tile>
<c-product-tile product-id="p2" name="Chair"></c-product-tile>
<p>Selected: {selectedId}</p>
</template>The parent adds one listener in connectedCallback and removes it in disconnectedCallback:
// productList.js
import { LightningElement } from 'lwc';
export default class ProductList extends LightningElement {
selectedId;
connectedCallback() {
this.template.addEventListener(
'productselected',
this.handleProductSelected
);
}
disconnectedCallback() {
this.template.removeEventListener(
'productselected',
this.handleProductSelected
);
}
handleProductSelected = (event) => {
this.selectedId = event.detail.productId;
};
}Clicking either button sets selectedId, and the template re-renders with the new value. The handler reads event.detail exactly as a template handler does. The event object is the same.
connectedCallback can run more than once if the component is removed and reinserted. Pairing the add in connectedCallback with the remove in disconnectedCallback keeps the listener count at one.
Stable references and this binding
The handler above is a class field holding an arrow function. This solves two problems at once.
thisbinding. An arrow function keepsthispointing at the component instance. If you pass a regular method (this.handleProductSelecteddeclared ashandleProductSelected(event) {...}),thisinside it will not be your component, andthis.selectedId = ...fails or does nothing useful. You would have to call.bind(this)yourself.- Removal.
removeEventListeneronly removes a listener when you pass the same function reference you added. An inline arrow function passed toaddEventListenercannot be removed later, because you have no reference to it. Calling.bind(this)inside both calls does not work either, since each call creates a new function.
Store the function once, as a field, and use that field in both calls.
Listening on a child element
Sometimes you want to listen to one specific child, or the event does not bubble. You can query the child and attach the listener directly. Do this in renderedCallback, because the child does not exist in the DOM until the template has rendered. Calling this.template.querySelector in connectedCallback returns null.
renderedCallback runs after every render, so a naive version adds a listener each time. The guard flag in the spine example prevents duplicates, but it has a flaw. If the child is removed and a new one is created later, the flag says "already listening" while the new element has no listener. A more reliable guard remembers which element has the listener:
// productList.js
import { LightningElement } from 'lwc';
export default class ProductList extends LightningElement {
showTile = true;
selectedId;
_tile;
toggleTile() {
this.showTile = !this.showTile;
}
renderedCallback() {
const tile = this.template.querySelector('c-product-tile');
if (tile === this._tile) {
return;
}
if (this._tile) {
this._tile.removeEventListener(
'productselected',
this.handleProductSelected
);
}
this._tile = tile;
if (tile) {
tile.addEventListener(
'productselected',
this.handleProductSelected
);
}
}
disconnectedCallback() {
if (this._tile) {
this._tile.removeEventListener(
'productselected',
this.handleProductSelected
);
this._tile = undefined;
}
}
handleProductSelected = (event) => {
this.selectedId = event.detail.productId;
};
}<!-- productList.html -->
<template>
<button onclick={toggleTile}>Toggle tile</button>
<template lwc:if={showTile}>
<c-product-tile product-id="p1" name="Desk"></c-product-tile>
</template>
<p>Selected: {selectedId}</p>
</template>Each time the tile appears or disappears, renderedCallback compares the current element with the remembered one. It detaches from the old element and attaches to the new one. The _tile field is not used in the template, so assigning it does not cause another render.
This example is only here to show the pattern. With lwc:if, a plain onproductselected={handleProductSelected} on the c-product-tile element does the same job with no JavaScript. Choose the programmatic form only when you have a reason from the list at the start of the chapter.
Template attribute or addEventListener
| Question | Template `on` attribute | `addEventListener` |
|---|---|---|
| Who removes the listener? | LWC | You |
| Works for a child that renders later? | Yes | Only if you attach after it renders |
| Needs `bubbles: true`? | No | On `this.template`, yes. On the child element, no |
| Supports options such as `once`? | No | Yes |
| Can listen to `window` or `document`? | No | Yes |
| Code to maintain | One attribute | Add, remove, and reference handling |
Common errors
- Nothing happens on
this.template. The child did not setbubbles: true. Add it to the event options. - The handler runs several times per event. Each render added a new anonymous listener, usually from
renderedCallbackwithout a guard. Use a stable function reference and an element check. Cannot set properties of undefinedinside the handler. The method lost itsthis. Use an arrow function class field.querySelectorreturnsnull. You called it before the first render, or the child is behind a falselwc:if. Query inrenderedCallbackand handlenull.- The query does not find an element inside a grandchild.
this.template.querySelectoronly sees elements in your own template. It does not reach into another component's template. - Handlers keep running after the component is removed. The listener was never removed. This matters most for
windowanddocumentlisteners, which outlive your component.
Exercise
A parent adds this.template.addEventListener('productselected', this.handleProductSelected) in connectedCallback. The child dispatches new CustomEvent('productselected', { detail: { productId: 'p1' } }). The handler never runs. What is wrong, and what is the smallest fix?
Show answer
The event does not bubble, so it never reaches the parent's template root. The fix is to add bubbles: true to the event options in the child. Alternatively, the parent could attach the listener directly to the child element in renderedCallback, which works without bubbling.
Exercise
A parent calls tile.addEventListener('productselected', (e) => this.log(e)) inside renderedCallback with no guard. After the component re-renders three times, one click logs four lines. Explain why, and list two changes that fix it.
Show answer
Each render adds a new listener with a new anonymous function, and the DOM only ignores a duplicate when the function reference is the same. After three re-renders there are four listeners on the element. Fix it by storing the handler as a class field arrow function and using that same reference in every call. Also remember which element already has the listener (for example in this._tile) and return early from renderedCallback when the element has not changed. Using the template attribute onproductselected removes the problem entirely.
Exercise
Why do both addEventListener and removeEventListener in a component usually use a class field arrow function instead of a method and .bind(this) written at each call?
Show answer
.bind(this) creates a new function every time it is called, so the function passed to removeEventListener is not the one passed to addEventListener, and the listener is never removed. A class field arrow function is created once per instance, keeps this bound to the component, and gives both calls the same reference.