Sub topic 4
Naming your event
This chapter covers how to choose the string passed to new CustomEvent(...). It assumes you can already write a child component that dispatches an event and a parent that listens for it. It also assumes you know that the parent's on<name> attribute connects to the child's event. The name looks like a minor detail, but it appears in two places that must agree exactly: the child's dispatchEvent call and the parent's on... attribute. Most "my event never fires" bugs in this area come from a mismatch between the two.
What the name does
An event name is the type of a DOM event. When the child calls dispatchEvent, the browser looks for listeners registered for exactly that string. A template attribute such as onproductselected={handler} is shorthand for registering a listener for the type productselected. The compiler takes the attribute name, removes the leading on, and uses the rest as the event type.
// Child
this.dispatchEvent(new CustomEvent('productselected'));<!-- Parent template -->
<c-product-tile onproductselected={handleProductSelected}></c-product-tile>The diagram shows how the two strings line up.
The last branch matters. A mismatched name raises no error. The event is dispatched, nobody is listening for that type, and the parent's handler never runs.
The naming rules
LWC documents a small set of rules for custom event names. Following them keeps the name compatible with the template syntax.
- Start with a lowercase letter.
- Use only lowercase letters, numbers, and underscores.
- Do not use uppercase letters, spaces, or hyphens.
- Do not prefix the name with
on.
| Name | Valid? | Why |
|---|---|---|
| `productselected` | Yes | Lowercase letters only. |
| `product_selected` | Yes | Underscore separates words. |
| `filter2changed` | Yes | Digits are allowed after the first letter. |
| `productSelected` | No | Contains an uppercase letter. |
| `product-selected` | No | Contains a hyphen. |
| `product selected` | No | Contains a space. |
| `onproductselected` | No | Starts with `on`, so the handler would be `ononproductselected`. |
| `2fast` | No | Does not start with a letter. |
Why uppercase fails
DOM event types are case-sensitive. If the child dispatches productSelected, only a listener registered for productSelected receives it. HTML attribute names, however, are case-insensitive, so the template attribute onproductSelected is read as onproductselected. The parent therefore listens for productselected while the child dispatches productSelected. These are different types, and the handler never runs.
// productTile.js (broken on purpose)
import { LightningElement, api } from 'lwc';
export default class ProductTile extends LightningElement {
@api productId;
handleClick() {
// Type is 'productSelected' (capital S)
this.dispatchEvent(
new CustomEvent('productSelected', {
detail: { productId: this.productId }
})
);
}
}<!-- productList.html: listens for 'productselected', never matches -->
<template>
<c-product-tile onproductselected={handleProductSelected}></c-product-tile>
</template>Nothing in the browser console tells you what went wrong. The fix is to use the all-lowercase name on both sides.
Why the `on` prefix is excluded
The template attribute is on plus the event name. If you name the event onproductselected, the parent must write ononproductselected={...}. That is confusing, and it hides the real event type. Name the event for what happened, and let the template syntax add the prefix.
Hyphens and underscores
In some frameworks, kebab-case event names such as item-selected are common. In LWC, use an underscore instead: item_selected, handled with onitem_selected. Many teams prefer a single run of lowercase letters, such as itemselected. Both are valid. The most important thing is to choose one style and apply it across the project.
Do not reuse standard event names
The rules do not stop you from naming an event click, change, select, focus, or input. Those are names of built-in DOM events, and reusing them causes trouble.
- A handler such as
onchange={handleChange}on a parent may receive both the native event and your custom one, and the two have different shapes. - Native events carry properties your custom event lacks. Code that assumes
event.target.valueexists will fail on a custom event that only hasdetail. - Other developers reading
onchangewill assume it is the native event.
Choose a name that describes your domain instead: valuechanged, productselected, rowdeleted.
// Avoid: collides with the native 'change' event
this.dispatchEvent(new CustomEvent('change', { detail: { value: this.value } }));
// Prefer: unambiguous, describes the outcome
this.dispatchEvent(new CustomEvent('valuechanged', { detail: { value: this.value } }));Some Salesforce base components, such as lightning-input, do dispatch events named change. They do so deliberately, to mimic the native behavior of an input. If your component is a drop-in replacement for a native control, that can be justified. Otherwise, pick a distinct name.
Name the fact, not the command
An event reports that something happened in the child. The parent decides what to do about it. A good name is a short past-tense phrase or a noun that describes the occurrence.
| Prefer | Avoid | Problem with the avoided name |
|---|---|---|
| `productselected` | `selectproduct` | Reads like an instruction to the parent. |
| `filterchanged` | `updatefilter` | Implies the parent must perform an update. |
| `dialogclosed` | `closedialog` | The child already closed itself, so this is a report, not a request. |
| `saved` | `dosave` | Mixes the action with the outcome. |
Naming the fact keeps the child independent. It does not need to know who listens, or what they do with the information. Two different parents can respond to productselected in different ways, and the child never changes.
There is one exception. When the child is asking the parent for permission or action, for example a cancelable event the parent can veto, a request-style name can be accurate. In most components, the past-tense form fits.
Keep names stable and discoverable
The event name is part of the component's public contract, just like an @api property. Parents in other files, and possibly other teams, depend on it. Renaming it later breaks every parent silently, because of the "no error on mismatch" behavior described above.
Some practical habits help.
- Put the event name next to the code that dispatches it, in a single place, instead of retyping the string in several methods.
- Document the name and the shape of
detailin a comment above the dispatching method. - Search the repository for
on<oldname>=before you rename anything.
Using a constant
Typing the same string twice invites typos. A module-level constant keeps the dispatch side consistent inside the component.
// productTile.js
import { LightningElement, api } from 'lwc';
const PRODUCT_SELECTED = 'productselected';
export default class ProductTile extends LightningElement {
@api productId;
@api name;
/**
* Fires 'productselected' when the tile is clicked.
* detail: { productId: string }
*/
handleClick() {
this.dispatchEvent(
new CustomEvent(PRODUCT_SELECTED, {
detail: { productId: this.productId }
})
);
}
}<!-- productTile.html -->
<template>
<button onclick={handleClick}>{name}</button>
</template>The parent's template still has to spell out the attribute by hand, since templates cannot reference JavaScript constants for attribute names. That is where a Jest test, shown below, protects you: it checks the exact string the child dispatches.
Names and propagation
By default, a custom event does not bubble, so only listeners on the child's own host element receive it. A name chosen for a non-bubbling event only needs to be unique among that child's own events.
If you later set bubbles: true, or add composed: true, the event travels further up the DOM, and other components may be listening for the same type. A generic name such as selected or updated can then trigger handlers in places you did not intend. For bubbling or composed events, prefer a more specific name, such as productselected over selected, or even a prefix that identifies your area, such as cart_itemadded. Underscores make this readable.
Checking the name in a test
A Jest test is a cheap way to lock the name in place. If someone changes the string to productSelected or product-selected, the test fails immediately.
// productTile.test.js
import { createElement } from 'lwc';
import ProductTile from 'c/productTile';
describe('c-product-tile event name', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('dispatches an event named productselected', () => {
const element = createElement('c-product-tile', { is: ProductTile });
element.productId = 'p1';
document.body.appendChild(element);
const handler = jest.fn();
element.addEventListener('productselected', handler);
element.shadowRoot.querySelector('button').click();
expect(handler).toHaveBeenCalledTimes(1);
});
});The test registers a listener for the exact lowercase name. A different dispatched name would leave handler uncalled, and the assertion would fail.
Common mistakes
- Camel case in the name.
new CustomEvent('productSelected')pairs withonproductselectedin HTML and never matches. - Hyphens copied from other frameworks.
item-selectedis outside the LWC rules. Useitemselectedoritem_selected. - Adding
onto the name. The handler attribute becomesononproductselected. - Reusing
click,change, orinput. Handlers may receive native events with a different shape. - A command-style name.
closedialogsuggests the parent must act.dialogclosedreports what occurred. - Renaming without searching parents. The mismatch causes no error, so the break goes unnoticed.
Exercise
A child component runs this.dispatchEvent(new CustomEvent('itemAdded', { detail: { id: 7 } })). The parent template contains <c-cart-item onitemAdded={handleAdd}></c-cart-item>, but handleAdd never runs. Explain why, and give the corrected dispatch call and template attribute, using an underscore to separate the two words.
Show answer
DOM event types are case-sensitive, but HTML attribute names are not. The parent attribute is read as onitemadded, so it listens for the type itemadded. The child dispatches itemAdded, which is a different type. Uppercase letters are also outside the LWC naming rules. Fix: dispatch new CustomEvent('item_added', { detail: { id: 7 } }) and use <c-cart-item onitem_added={handleAdd}></c-cart-item>. The all-lowercase single-word form itemadded with onitemadded is equally valid.
Exercise
Choose the better event name for each situation and say why: (a) a child reports that the user finished editing and the parent should decide what to do next, choosing between finishedit and editfinished; (b) a child wants to announce that its text field changed, choosing between change and valuechanged.
Show answer
(a) editfinished. It states a fact that already happened, so the child does not tell the parent what to do. (b) valuechanged. The name change is also a native DOM event, so a parent onchange handler could receive native events with a different shape, and readers would assume it is the native event. A domain-specific name avoids that confusion.