Skip to content
tezvyn:

CustomEvent: Sending Custom Data with Events

Source: developer.mozilla.orgEasyHow cards are made

CustomEvent: Sending Custom Data with Events

CustomEvent lets components communicate without direct coupling by firing custom-named events. It's like a private broadcast system for your app. Use it for a child component to signal a parent, passing data in the detail property. Don't forget detail!

Why it exists

In a complex web application, different components need to communicate. Direct function calls create tight coupling, making code brittle and hard to refactor. We need a way for a component to announce that something has happened without being directly tied to the components that need to react to that change.

The mental model

Think of CustomEvent as an internal, private broadcast system for your application. One component acts as a radio station, broadcasting a signal on a specific frequency (the event name). Other components can tune into that frequency by adding an event listener. The signal itself can carry a package of information, which is the detail property.

How it works

There are three steps. First, create the event: const myEvent = new CustomEvent('user-login', { detail: { userId: 123 } });. The first argument is the event's name, and the detail object contains your custom data. Second, have an element listen for it: document.addEventListener('user-login', (e) => { console.log(e.detail.userId); });. Third, dispatch the event from a source element: loginButton.dispatchEvent(myEvent);. The event will then propagate (or bubble) up the DOM tree from the loginButton.

When to use it

Use CustomEvent to decouple components. It's perfect for when a child or deeply nested element needs to signal a state change to a parent or ancestor container. For example, a button inside a modal can dispatch a close-modal event, and the page's main script can listen for it to remove the modal from the DOM. The button doesn't need to know anything about the main script.

When not to use it

For simple parent-to-child communication, passing a function as a prop is often clearer and more direct. For communication between different browser windows, tabs, or with a service worker, Window.postMessage() is the correct tool. If you only need to pass a string, CustomEvent works, but its real power is in passing structured data objects via the detail property.

One canonical example

A shopping cart icon in the header needs to update its item count when a user clicks an "Add to Cart" button on a product page. The button, upon being clicked, dispatches a CustomEvent named item-added. The header component listens for the item-added event on the document and, upon receiving it, updates its count. The button component and header component never know about each other.

Interview question

What is the main advantage of using CustomEvent for communication between different parts of a web application?

  • a.It is the recommended method for passing data from a parent component to its immediate child.
  • b.It provides a secure way to exchange messages between different browser tabs or windows.
  • c.It allows for direct function calls between any two components in the DOM.
  • d.It facilitates a broadcast mechanism that decouples components from direct dependencies.Correct
Why?

CustomEvent's primary benefit is to enable components to broadcast information without creating tight coupling, acting as a 'private broadcast system.' Option A is incorrect because the card states that passing a function as a prop is often clearer for simple parent-to-child communication.

Just read this? Test yourself on what you have been reading.

Read the original → developer.mozilla.org

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on javascript — each one lists the topics its interview covers.

See open roles