TalentJR

🟨 JavaScript tutorial for beginners · Class 9 · Lesson 16 of 18 · Free

Event-Driven Architecture – Build JavaScript Apps Around Events

⏱ About 35 minutes · ▶ run real JavaScript here — nothing to install · no sign-in

In this lesson you will

  • Use the event object to find out what happened and where
  • Create, send and listen to your own custom events
  • Build an app from parts that talk only through events

When the school bell rings, nobody shouts every student's name. Teachers, students and the canteen each hear the bell and do their own job. Event-driven apps work like that: one part announces "something happened", and every part that cares reacts — without knowing about each other.

What is event-driven programming in JavaScript?

Most programs run top to bottom and stop. An event-driven program sets up listeners and then WAITS. Code runs only when an event happens: a click, a key press, a message, a timer.

Every listener gets an event object. `e.type` says what happened and `e.target` says which element it happened on.

Click the buttons and watch the console.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Listeners ready. Waiting for clicks…

💡 Notice: we pass handleClick, without (). The browser calls it later, when a click happens.

How do I create custom events in JavaScript?

You can invent your own events with `new CustomEvent("name", { detail: data })`. The `detail` carries any data you like.

`EventTarget` is a plain object that can have listeners — every button is one, and you can make your own with `new EventTarget()`.

`dispatchEvent` sends the event. It runs every listener RIGHT AWAY, in the order they were added, before the next line.

🎬 How JavaScript thinks — step 1 of 8JavaScript is about to run line 1
▶const match = new EventTarget();
2
3match.addEventListener("wicket", (e) => {
4 console.log("Scoreboard: wickets =", e.detail.wickets);
5});
6match.addEventListener("wicket", (e) => {
7 console.log("Commentary:", e.detail.batter, "is out!");
8});
9
10match.dispatchEvent(new CustomEvent("wicket", {
11 detail: { batter: "Rohit", wickets: 1 }
12}));
13console.log("Next ball");
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
Scoreboard: wickets = 1
Commentary: Rohit is out!
Next ball

💡 Try it: add a third listener that prints "Crowd: Oooh!".

How do I build my own event emitter in JavaScript?

An event emitter is the bell system written by you. It keeps an object like `{ message: [fn1, fn2] }` — a list of listener functions for each event name.

`on(name, fn)` adds a function to the list. `emit(name, data)` calls every function in that list. That is the whole trick!

Node.js and many libraries are built on exactly this idea.

🎬 How JavaScript thinks — step 1 of 14JavaScript is about to run line 14
1function createEmitter() {
2 const listeners = {};
3 return {
4 on(name, fn) {
5 listeners[name] = listeners[name] || [];
6 listeners[name].push(fn);
7 },
8 emit(name, data) {
9 (listeners[name] || []).forEach((fn) => fn(data));
10 }
11 };
12}
13
▶const chat = createEmitter();
15chat.on("message", (m) => console.log(`${m.from}: ${m.text}`));
16chat.on("message", () => console.log("🔔 ding"));
17chat.emit("message", { from: "Asha", text: "Tiffin break?" });
18chat.emit("typing", { from: "Rohan" });
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
Asha: Tiffin break?
🔔 ding

💡 The "typing" event has no listeners, so nothing happens — and that is fine.

What is event delegation in JavaScript?

Ten buttons with ten listeners is a lot. Event delegation: put ONE listener on the parent. Clicks "bubble" up from the clicked element to its parents, so the parent hears them all.

`e.target.closest("li")` finds which item was clicked. A big bonus: items you add later work too, with no new listener.

Click a train to select it, then add a new train and click it.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
One listener for 2 trains

💡 Try it: click "Add a train" twice, then click the new trains. They work without any new listener.

How do I build an app from parts that talk with events?

Now the big idea, event-driven architecture. The form part does not know about the list or the counter. It only announces: "task:added".

The list part and the counter part each listen for that event and do their own job. Want a new part, like a sound? Add one more listener — no other code changes.

This is called loose coupling: parts are connected only by event names, like students and the school bell.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Added: Maths page 42 | total 1

💡 Try it: add Part 4, a listener that logs "Well done!" when count reaches 3.

🤔 Predict the output

Think like JavaScript: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

const bell = new EventTarget();
bell.dispatchEvent(new Event("ring"));
bell.addEventListener("ring", () => console.log("Ring!"));
bell.dispatchEvent(new Event("ring"));
console.log("End");

Question 2. What does this print?

const t = new EventTarget();
t.addEventListener("goal", () => console.log("B"));
console.log("A");
t.dispatchEvent(new Event("goal"));
console.log("C");

Question 3. What does this print?

const door = new EventTarget();
let knocks = 0;
door.addEventListener("knock", () => knocks++, { once: true });
door.dispatchEvent(new Event("knock"));
door.dispatchEvent(new Event("knock"));
console.log(knocks);

🧩 Your challenge

Class group chat: use the createEmitter() from this lesson. Add three listeners to "message": one prints "Asha: Hi", one counts unread messages, one prints "⚠️ Teacher says: ..." ONLY when the sender is "Teacher". Emit the three messages given, then print the unread count. Expected output: Asha: Hi Rohan: Did you finish maths? Teacher: Test on Monday ⚠️ Teacher says: Test on Monday Unread: 3

Expected output in the console:
Asha: Hi
Rohan: Did you finish maths?
Teacher: Test on Monday
⚠️ Teacher says: Test on Monday
Unread: 3
🟨 JavaScript — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

function sayHi() {
  console.log("Hi!");
}
document.querySelector("#hi").addEventListener("click", sayHi());

No error, but "Hi!" prints once immediately when the page loads, and clicking the button does nothing — sayHi() ran right away and gave undefined to addEventListener.

✅ Right

function sayHi() {
  console.log("Hi!");
}
document.querySelector("#hi").addEventListener("click", sayHi);
console.log("Click the button");

Pass the function itself (sayHi), not its result (sayHi()). The browser will call it at click time.

❌ Wrong

const match = new EventTarget();
match.addEventListener("four", (e) => console.log("Runs:", e.detail.runs));
match.dispatchEvent(new Event("four", { detail: { runs: 4 } }));

TypeError: Cannot read properties of undefined (reading 'runs')

✅ Right

const match = new EventTarget();
match.addEventListener("four", (e) => console.log("Runs:", e.detail.runs));
match.dispatchEvent(new CustomEvent("four", { detail: { runs: 4 } }));

A plain Event has no detail. To send data with your event, use CustomEvent.

❌ Wrong

const bus = new EventTarget();
bus.addEventListener("task-added", () => console.log("List updated"));
bus.dispatchEvent(new Event("taskAdded"));
console.log("Done");

No error, but "List updated" never prints — "taskAdded" and "task-added" are different names, and JavaScript does not warn you.

✅ Right

const TASK_ADDED = "task-added";
const bus = new EventTarget();
bus.addEventListener(TASK_ADDED, () => console.log("List updated"));
bus.dispatchEvent(new Event(TASK_ADDED));
console.log("Done");

Event names must match exactly. Keep each name in one const and use that everywhere, so a typo becomes a clear error.

📌 Remember

  • Event-driven code sets up listeners and waits; code runs when something happens.
  • The event object tells you what happened (e.type) and where (e.target).
  • new CustomEvent(name, { detail }) + dispatchEvent lets you send your own events with data.
  • Event delegation: one listener on the parent handles all children, even new ones.
  • Parts that talk only through events are loosely coupled — easy to add, remove and change.

Finished the quiz and the challenge?

Questions students ask

What is event-driven architecture in simple words?

It is a way to build an app where parts do not call each other directly. One part announces an event, like "order placed", and any part that cares listens and reacts. Web pages, games, chat apps and Node.js servers all work this way.

What is the difference between Event and CustomEvent in JavaScript?

Both create an event you can dispatch. CustomEvent also has a detail property, so you can send data along with it, like the task text or the runs scored.

How do I remove an event listener?

Call removeEventListener with the same event name and the SAME function you added. That is why you should keep the function in a named variable. Or add the listener with { once: true } if it should run only once.

What does event bubbling mean?

When you click an element, the click event first fires on it and then travels up to its parent, grandparent and so on up to the document. Event delegation uses this. You can stop it with e.stopPropagation(), but you rarely need to.