Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.8 — Custom Events
JavaScript · Example 1 of 3

A cart that listens for cart:add

Delete the analytics listener and the cart still works; delete the cart listener and the cards still work. That's decoupling.

You can invent your own events: new CustomEvent("cart:add", { detail, bubbles: true }) creates one, element.dispatchEvent(event) fires it, and any code listening for that name reacts, so parts of an app can talk to each other without knowing about each other.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Make a <button id="like"> dispatch a bubbling post:like event with detail: { postId: 42 }, and a document listener that logs liked post 42. Click it from code.

02

Create a tiny event bus with new EventTarget() that has a notify event. Subscribe two listeners and dispatch once with the message Saved.

Explain it without notes

01

How do you create and dispatch a custom event with data?

02

What does it mean that custom events decouple components? Give an example.

03

What does the return value of dispatchEvent tell you, and how can you use it?

A cart that listens for cart:add

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

cart:add { id: 1, name: 'Masala tea', price: 120 } | target: <div.card>
analytics: track 1
cart:add { id: 2, name: 'Samosa', price: 30 } | target: <div.card>
analytics: track 2