Sub topic 11
Designing Events Well
This chapter assumes you can already create and dispatch a CustomEvent, listen for it in a parent template, and read event.detail. It covers the design choices that keep events easy to use and hard to misuse.
Name events for what happened
An event reports a fact about the child. It does not give orders to the parent. Name it after the thing that happened, in the past tense or as a plain noun.
- Use lowercase letters only. Digits and underscores are allowed, but do not start or end with an underscore.
- Do not use hyphens, spaces, or uppercase letters. The parent's
onattribute is built from the name, and the name must stay a valid lowercase attribute. - Do not start the name with
on. The parent adds that prefix itself. - Avoid names that collide with native events, such as
click,change, orselect.
| Weak name | Better name | Reason |
|---|---|---|
| `selectProduct` | `productselected` | Uppercase letters are not allowed. |
| `onselected` | `productselected` | The `on` prefix would double up (`ononselected`). |
| `deleteitem` | `itemdeleted` | Describes what happened, not what the parent must do. |
| `change` | `quantitychanged` | Avoids a clash with the native `change` event. |
Keep the payload small and safe
Put only what the parent needs into detail. Send identifiers and primitive values, not component internals.
// Good: a small, plain object
this.dispatchEvent(
new CustomEvent('productselected', {
detail: { productId: this.productId }
})
);Follow these rules:
- Send plain data, such as strings, numbers, booleans, and simple objects. Do not send
this, DOM elements, or template references. - Do not pass your own tracked objects or arrays and let the parent change them. Both components would then share one object. Send a copy if the parent might modify it.
- Use the same payload shape every time. If
detailis sometimes a string and sometimes an object, every parent needs extra checks. - Send an object for
detail, even for one value.{ productId }can gain a field later without breaking existing parents. A bare string cannot.
// Safer when the payload is a list the parent might edit
this.dispatchEvent(
new CustomEvent('filterschanged', {
detail: { filters: [...this.filters] }
})
);Start with the narrowest propagation
By default a custom event does not bubble and is not composed. Only listeners on the child element itself receive it. That is the safest setting, so keep it until you have a reason to change it.
bubbles: truelets elements between the child and the root of the parent's template receive the event. Use it when a wrapper element needs to handle events from several children.composed: truelets the event cross shadow boundaries. Any ancestor component can then hear it, which couples unrelated components to your event name. Avoid it unless you truly need it.
flowchart TDDo not change state in the child and expect the parent to follow
Events describe what the child saw. The parent decides what to do. Avoid designs where the child assumes a result.
- The child dispatches
itemdeleted. The parent removes the item and passes new data down. - Do not make the child remove its own row and also fire an event, because the two views of the data can drift apart.
Also keep events to one job. If a handler needs a long list of flags in detail to know which case it is in, split the event into two events with clearer names.
Document the contract
An event is part of your component's public interface, like an @api property. State its name and detail shape where other developers will find it, for example in a comment above the dispatch.
/**
* Fired when the user picks a product.
* @event productselected
* @property {string} detail.productId - Id of the chosen product.
*/
handleClick() {
this.dispatchEvent(
new CustomEvent('productselected', {
detail: { productId: this.productId }
})
);
}Add a Jest test for each event, as in the previous chapter. The test then guards the name and the payload shape against accidental change.
Checklist
- The name is lowercase, has no
onprefix, and says what happened. detailis a plain object with only the data the parent needs.- Arrays and objects are copied before sending if the parent could change them.
bubblesandcomposedare left off unless a specific need is documented.- The event has a comment and a Jest test.
Exercise
A child dispatches new CustomEvent('ItemDeleted', { detail: this.item, composed: true, bubbles: true }), where this.item is an object the child keeps using. Name three problems and give a corrected call.
Show answer
First, the name has uppercase letters, so the parent cannot reliably listen with onitemdeleted. Second, detail is the child's own object, so the parent could change the child's data, and a bare object also cannot grow new fields cleanly. Third, composed: true and bubbles: true let unrelated ancestors hear a generic event without a stated need. Corrected: new CustomEvent('itemdeleted', { detail: { itemId: this.item.id } }).
Exercise
Why should the event be named quantitychanged and not change?
Show answer
change is a native DOM event name, so a handler could be triggered by native events or confuse readers. quantitychanged is specific and cannot collide.