Sub topic 3
Adding a Listener with `addEventListener` in LWC
Assume you know basic JavaScript, LWC templates, @api, and component composition. Most parent components should listen in the template. Use addEventListener when the element is conditional, discovered dynamically, or needs a listener configured in JavaScript.
Adding a listener with `addEventListener`
Query the child from the parent template, then register a listener after rendering. Guard the registration so each render does not add another listener.
import { LightningElement } from 'lwc';
export default class ProductList extends LightningElement {
listening = false;
renderedCallback() {
const tile = this.template.querySelector('c-product-tile');
if (tile && !this.listening) {
tile.addEventListener('productselected', this.handleProductSelected);
this.listening = true;
}
}
handleProductSelected = (event) => {
console.log(event.detail.productId);
};
}An arrow-function field preserves the component instance as this. Remove the listener when your code can replace or discard the target element.
Bubbling and shadow boundaries
A custom event normally reaches the element on which the child dispatches it. Set bubbles: true when an ancestor inside the same template should receive it.
this.dispatchEvent(new CustomEvent('productselected', {
detail: { productId: this.productId },
bubbles: true
}));composed: true allows the event to cross a shadow boundary. This makes the event visible outside the child’s encapsulated template. Use it only when that public event contract is intentional. Prefer a direct parent listener when possible.
Testing dispatched events with Jest
Mount the component, attach a listener to its host element, trigger the action, and inspect event.detail.
const handler = jest.fn();
element.addEventListener('productselected', handler);
element.shadowRoot.querySelector('button').click();
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0][0].detail.productId).toBe('p1');Designing events well
- Use lowercase names such as
productselected. - Name the event after the business action, not the UI control.
- Send a small, documented
detailobject. - Keep the payload stable and avoid exposing mutable internal state.
- Use
bubblesandcomposedonly when the event needs wider propagation.
When events are not the right tool
Events fit one-way notifications from a child to an ancestor. Use public methods when the parent needs to command a child directly. Use shared state or Lightning Message Service when unrelated components need to communicate. Use public properties for data flowing from parent to child.
Exercise
Why should a programmatic listener be guarded in renderedCallback()?
Show answer
Rendering can happen many times. Without a guard, the same event can trigger multiple handlers for one dispatch.