Phase 11 — Events (Very Important)
Module 38.3 — Custom Events & Advanced Event Handling
As JavaScript applications grow larger, different components need to communicate with each other. Instead of tightly coupling components, JavaScript provides Custom Events that allow one component to notify another when something happens.
Custom Events are widely used in:
- Single Page Applications (SPA)
- Component-based UI
- Dashboards
- Notification Systems
- Shopping Carts
- Chat Applications
- Games
- Plugins
Event-Driven Architecture
1User Action 2 │ 3 ▼ 4Component A 5 │ 6dispatchEvent() 7 │ 8 ▼ 9Custom Event 10 │ 11 ▼ 12Component B 13 │ 14 ▼ 15Update UI
Instead of directly calling another function, a component dispatches an event, and any interested component can listen for it.
Overview
| Feature | Purpose |
|---|---|
dispatchEvent() | Dispatch an event manually |
CustomEvent | Create your own events |
detail | Pass custom data |
| Event-driven Architecture | Loose communication |
| Component Communication | Share information between modules |
dispatchEvent()
The dispatchEvent() method manually triggers an event.
Syntax
1element.dispatchEvent(event);
Basic Example
1<button id="btn"> 2 3Click 4 5</button>
1const button = document.getElementById("btn"); 2 3button.addEventListener("click", () => { 4 5 console.log("Button Clicked"); 6 7}); 8 9button.dispatchEvent(new Event("click"));
Output
1Button Clicked
Even though the user didn't click the button, JavaScript triggered the event.
Creating a Custom Event
The CustomEvent constructor creates events with custom names.
1const event = new CustomEvent("login");
Dispatch it
1document.dispatchEvent(event);
Listen for it
1document.addEventListener("login", () => { 2 3 console.log("User Logged In"); 4 5});
Passing Data with detail
One of the biggest advantages of CustomEvent is the ability to send data.
1const loginEvent = new CustomEvent( 2 3 "login", 4 5 { 6 7 detail: { 8 9 username: "Ankit", 10 11 role: "Admin" 12 13 } 14 15 } 16 17); 18 19document.dispatchEvent(loginEvent);
Receive the data
1document.addEventListener("login", (event) => { 2 3 console.log(event.detail.username); 4 5 console.log(event.detail.role); 6 7});
Output
1Ankit 2Admin
Multiple Listeners
Many components can listen to the same custom event.
1document.addEventListener("login", () => { 2 3 console.log("Header Updated"); 4 5}); 6 7document.addEventListener("login", () => { 8 9 console.log("Dashboard Loaded"); 10 11}); 12 13document.addEventListener("login", () => { 14 15 console.log("Notifications Loaded"); 16 17});
One event updates multiple parts of the application.
Event Names
Use descriptive names.
Good Examples
1userLogin 2userLogout 3cartUpdated 4themeChanged 5productAdded 6messageReceived 7profileUpdated
Avoid
1event1 2abc 3test
Practical Example — Theme Switcher
1const themeChanged = new CustomEvent( 2 3 "themeChanged", 4 5 { 6 7 detail: { 8 9 theme: "dark" 10 11 } 12 13 } 14 15); 16 17document.dispatchEvent(themeChanged); 18 19document.addEventListener( 20 21 "themeChanged", 22 23 (event) => { 24 25 document.body.dataset.theme = event.detail.theme; 26 27 } 28 29);
Real-World Example — Shopping Cart
Add Product
1const cartEvent = new CustomEvent( 2 3 "cartUpdated", 4 5 { 6 7 detail: { 8 9 items: 5 10 11 } 12 13 } 14 15); 16 17document.dispatchEvent(cartEvent);
Update Cart Icon
1document.addEventListener( 2 3 "cartUpdated", 4 5 (event) => { 6 7 document.getElementById( 8 9 "count" 10 11 ).textContent = event.detail.items; 12 13 } 14 15);
Mini Project — Notification System
HTML
1<button id="notify"> 2 3Notify 4 5</button> 6 7<h2 id="message"></h2>
JavaScript
1const button = document.getElementById("notify"); 2 3const message = document.getElementById("message"); 4 5document.addEventListener( 6 7 "showNotification", 8 9 (event) => { 10 11 message.textContent = event.detail.text; 12 13 } 14 15); 16 17button.addEventListener("click", () => { 18 19 const notification = new CustomEvent( 20 21 "showNotification", 22 23 { 24 25 detail: { 26 27 text: "Welcome to JavaScript!" 28 29 } 30 31 } 32 33 ); 34 35 document.dispatchEvent(notification); 36 37});
Real-World Example — User Login
1document.addEventListener( 2 3 "userLogin", 4 5 (event) => { 6 7 console.log( 8 9 `Welcome ${event.detail.name}` 10 11 ); 12 13 } 14 15); 16 17const login = new CustomEvent( 18 19 "userLogin", 20 21 { 22 23 detail: { 24 25 name: "Ankit" 26 27 } 28 29 } 30 31); 32 33document.dispatchEvent(login);
Event-Driven Dashboard
1Login 2 │ 3 ▼ 4dispatchEvent("userLogin") 5 │ 6 ├────────► Header 7 │ 8 ├────────► Sidebar 9 │ 10 ├────────► Dashboard 11 │ 12 ├────────► Notifications 13 │ 14 └────────► Analytics
Every component updates independently.
Common Mistakes
Using Generic Event Names
❌ Bad
1new CustomEvent("event");
✅ Better
1new CustomEvent("cartUpdated");
Forgetting to Pass Data
1new CustomEvent("login");
Better
1new CustomEvent( 2 3 "login", 4 5 { 6 7 detail: { 8 9 user: "Ankit" 10 11 } 12 13 } 14 15);
Calling Functions Directly
Instead of
1updateCart(); 2 3updateHeader(); 4 5updateSidebar();
Dispatch a single event
1document.dispatchEvent( 2 3 new CustomEvent("cartUpdated") 4 5);
Each component can respond independently.
Best Practices
- Use descriptive event names such as
userLogin,themeChanged, orcartUpdated. - Pass structured data through the
detailproperty instead of using global variables. - Use custom events to decouple independent components.
- Avoid excessive use of global document events in very large applications; consider dispatching events from the most relevant element.
- Document custom event names and payload structures in larger projects.
Interview Questions
Q1. What is dispatchEvent()?
It manually triggers an event on an element, allowing event listeners to respond even without direct user interaction.
Q2. What is CustomEvent?
CustomEvent is a constructor used to create user-defined events with optional custom data.
Q3. What is the purpose of the detail property?
The detail property carries additional data that event listeners can access through event.detail.
Q4. Why are custom events useful?
They enable communication between independent components without tightly coupling them, making applications easier to maintain and extend.
Q5. What is event-driven architecture?
Event-driven architecture is a design pattern where components communicate by emitting and listening for events rather than directly calling each other's functions.
Summary
In this module, you learned how to create and dispatch custom events using dispatchEvent() and CustomEvent. You explored how to pass data with the detail property, build event-driven communication between components, and implement practical examples such as notifications, shopping carts, and theme switching. These concepts are widely used in modern JavaScript frameworks and large-scale frontend applications.
Next Phase: Phase 12 — Browser APIs, where you'll learn essential browser features including Local Storage, Session Storage, Cookies, Fetch API, Clipboard API, Geolocation API, History API, URL API, Web Workers, Notifications API, Intersection Observer, Mutation Observer, Resize Observer, and more used in professional web development.