Sub topic 3
Dispatching the Event from the Child
What this chapter assumes
You know basic JavaScript classes and modules, the structure of an LWC component (an HTML template plus a JavaScript class), how to expose a property with @api, and how to place one component inside another's template. The previous chapter showed how to build a CustomEvent. This chapter covers the next step: sending that event so the parent can receive it.
Creating an event does nothing by itself. new CustomEvent('productselected') produces an object in memory. The parent hears about it only after the child dispatches it.
Dispatching in one line
Every LWC class inherits a dispatchEvent method. You pass it an event object, and the event is fired on the component's host element. The host element is the tag the parent wrote, such as <c-product-tile>.
// 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 }
})
);
}
}The template connects a native browser event to this method:
<!-- productTile.html -->
<template>
<button onclick={handleClick}>{name}</button>
</template>Two events are involved here, and it helps to keep them apart:
- The native
clickevent happens inside the child's template. The parent never sees it, because it does not cross the child's shadow boundary. - The custom
productselectedevent is the one the child chooses to announce. It is the child's public signal, much like an@apiproperty is its public input.
In other words, the child translates a low-level DOM event into a meaningful domain event. The parent then reacts to "a product was selected" and needs no knowledge of buttons.
What dispatchEvent does internally
dispatchEvent is synchronous. When the call runs, the browser walks through every listener registered for that event type on the host element and runs each one. Only after all of them finish does dispatchEvent return, and the next line of your child code runs after that.
Because of that ordering, the diagram below uses the real order of calls.
Three consequences follow from this model:
- If the parent's handler throws an error, the error is reported by the browser, but the child's code continues. Listener errors do not propagate back through
dispatchEvent. - A slow parent handler delays the child. Keep handlers short, and start asynchronous work instead of waiting on it.
- If nothing is listening,
dispatchEventdoes nothing and returnstrue. There is no error for an unheard event. This is why a typo in an event name fails silently.
Where you can call dispatchEvent
You can dispatch from any code that runs after the component exists. The common places differ in how safe they are.
| Location | Works? | Notes |
|---|---|---|
| A template handler such as `handleClick` | Yes | The normal case. A user action triggers the signal. |
| After a `Promise` or `async` call resolves | Yes | Common for "save finished" or "load finished" signals. |
| `connectedCallback` | Yes, with care | Fine for a one-time "I am ready" signal. Listeners declared in the parent template already exist at this point. |
| `renderedCallback` | Risky | Runs after every render. An event that makes the parent change state can cause another render, then another event. |
| `constructor` | No | LWC throws an error, because the component is not yet attached to the DOM. |
The constructor restriction is easy to hit when you want to announce "created". Move that call to connectedCallback.
// statusBadge.js
import { LightningElement } from 'lwc';
export default class StatusBadge extends LightningElement {
connectedCallback() {
this.dispatchEvent(new CustomEvent('badgeready'));
}
}Dispatching after asynchronous work
The event does not need to fire inside the click handler. Often the right moment is when some operation completes. The next example simulates a save and dispatches only when it succeeds.
// itemEditor.js
import { LightningElement, api } from 'lwc';
export default class ItemEditor extends LightningElement {
@api recordName = 'New item';
isSaving = false;
saveItem() {
// Stand-in for a real server call.
return new Promise((resolve) => {
setTimeout(() => resolve({ id: 'item-42' }), 100);
});
}
async handleSave() {
this.isSaving = true;
try {
const result = await this.saveItem();
this.dispatchEvent(
new CustomEvent('itemsaved', {
detail: { id: result.id }
})
);
} catch (error) {
this.dispatchEvent(
new CustomEvent('itemerror', {
detail: { message: error.message }
})
);
} finally {
this.isSaving = false;
}
}
}Note the design. The component reports both outcomes as separate events and leaves the decision about what to do to the parent. A child that shows a toast or navigates away itself is harder to reuse.
The return value and cancelable events
dispatchEvent returns a boolean. It is false only when two conditions hold: the event was created with cancelable: true, and a listener called event.preventDefault(). In every other case it returns true.
This gives the parent a way to veto an action in the child. The child asks, and the parent may refuse.
// itemRow.js
import { LightningElement, api } from 'lwc';
export default class ItemRow extends LightningElement {
@api itemId;
deleted = false;
handleDelete() {
const allowed = this.dispatchEvent(
new CustomEvent('beforedelete', {
detail: { itemId: this.itemId },
cancelable: true
})
);
if (allowed) {
this.deleted = true;
}
}
}The parent vetoes by calling preventDefault() in its handler:
// itemList.js
import { LightningElement } from 'lwc';
export default class ItemList extends LightningElement {
handleBeforeDelete(event) {
if (!window.confirm('Delete this item?')) {
event.preventDefault();
}
}
}Because dispatch is synchronous, the parent's handler has finished by the time allowed is assigned. This is one of the few places where a result flows from parent back to child, and it works only because of that ordering.
Create a fresh event each time
An event object is a small record of one occurrence. Build a new CustomEvent for every dispatch. Do not store one in a field and send it repeatedly.
Reusing an event object invites bugs. A listener may have changed its state, for example by calling preventDefault(), and an event dispatched twice can also fail while a dispatch is still in progress. Creating a new event is cheap, so there is no benefit to caching.
Protect the detail payload
The detail object is passed by reference, so the parent receives the same object your child holds. That raises two risks:
- If the child changes the object after dispatching, the parent may see the change later, for example if it stored
event.detailin a field. - If the parent changes the object, it may alter the child's internal state.
Send small, plain values, and copy anything the child will keep working with.
// selectionBar.js
import { LightningElement } from 'lwc';
export default class SelectionBar extends LightningElement {
selectedIds = ['a1', 'b2'];
handleApply() {
this.dispatchEvent(
new CustomEvent('selectionapplied', {
detail: { ids: [...this.selectedIds] }
})
);
}
}Spreading the array into a new one gives the parent its own copy. Inside LWC, objects held in tracked or reactive state may also be wrapped in read-only proxies, which makes mutation attempts fail in confusing ways. A plain copy avoids both problems. The full set of rules for payloads comes in a later chapter on the detail property.
Common mistakes
Dispatching on the wrong target. this.dispatchEvent(...) fires on the host element, which is what the parent listens to. this.template.dispatchEvent(...) fires on the shadow root inside the child. A non-bubbling event sent there never reaches the parent's on... handler. Use this unless you have a specific reason not to.
Forgetting that the event name must match. The string passed to CustomEvent and the attribute in the parent are linked by name. An event named productselected is heard by onproductselected. If the child uses 'productSelected' or 'product-selected', the parent's handler will not run, and nothing warns you. The next chapter covers the naming rules in detail.
Dispatching in renderedCallback without a guard. If the parent's handler changes a field that the child receives, the child renders again, renderedCallback runs again, and the event fires again. Dispatch from user actions or from one-time lifecycle hooks instead.
Expecting a disabled control to dispatch. A browser does not fire click on a disabled button, so handleClick never runs and no custom event is sent. If an event is missing, confirm that the native event fires first.
Treating dispatch as a function call with a result. Except for the cancelable case above, do not rely on the parent to compute something and hand it back. If the child needs data, the parent should pass it down through an @api property.
A debugging checklist
When a dispatched event does not reach the parent, check these in order:
- Does the native trigger run? Put a
console.logat the top of the child's handler. - Is
dispatchEventreached, or does an earlier line throw? - Does the event type string match the parent's attribute after removing
on, character for character? - Is the parent's listener on the child's own tag, not on an unrelated element?
- Are you calling
this.dispatchEventand notthis.template.dispatchEvent? - If you rely on
bubblesorcomposed, are both set the way your component tree needs? Propagation is covered in a later chapter.
Exercise
A child component calls this.dispatchEvent(new CustomEvent('itemsaved')) inside an async method, after await this.saveItem(). The parent's handler takes 200 ms to finish. Does the next line after dispatchEvent in the child run before or after that handler completes, and why?
Show answer
It runs after. dispatchEvent is synchronous, so every listener on the host element runs to completion before dispatchEvent returns. The child's next line therefore starts only after the parent's 200 ms handler has finished. The parent should keep handlers short, or start asynchronous work instead of waiting on it.
Exercise
A child dispatches new CustomEvent('beforedelete', { detail: { itemId: this.itemId } }) and then checks the return value of dispatchEvent to decide whether to remove the row. The parent calls event.preventDefault(), yet the row is still removed. What is wrong, and how do you fix it?
Show answer
The event was not created with cancelable: true, so preventDefault() has no effect and dispatchEvent always returns true. Add cancelable: true to the options object: new CustomEvent('beforedelete', { detail: { itemId: this.itemId }, cancelable: true }). After that, dispatchEvent returns false when the parent vetoes the action, and the child can skip the removal.