JavaScript - Custom Events

Overview

Estimated time: 10–15 minutes

Custom events allow you to define and dispatch your own events for advanced communication between components.

Learning Objectives

  • Create and dispatch custom events.
  • Listen for custom events on DOM elements.

Prerequisites

Creating Custom Events

const myEvent = new CustomEvent('myEvent', { detail: { foo: 42 } });
document.dispatchEvent(myEvent);

Listening for Custom Events

document.addEventListener('myEvent', function(event) {
  console.log(event.detail.foo); // 42
});

Common Pitfalls

  • Custom events do not bubble by default unless specified.

Summary

Custom events are powerful for decoupling components and building modular applications.