Question 10
Back to Exercise
The page contains this HTML:
<div id="app"><div id="catalog"><button data-id="c1" data-price="499">JS Course</button><button data-id="c2" data-price="299">DOM Workbook</button></div><span id="badge">0</span><p id="summary"></p></div>The catalog should not know about the cart badge or the summary. Make the catalog dispatch a bubbling "cart:add" CustomEvent with the item in detail, and let the badge and summary components listen for it on #app.
Solution
const app = document.getElementById("app");
// Catalog component: only announces what happened
document.getElementById("catalog").addEventListener("click", (e) => {
const btn = e.target.closest("button");
if (!btn) return;
btn.dispatchEvent(new CustomEvent("cart:add", {
bubbles: true,
detail: { id: btn.dataset.id, title: btn.textContent, price: Number(btn.dataset.price) },
}));
});
// Badge component
let count = 0;
app.addEventListener("cart:add", () => {
document.getElementById("badge").textContent = ++count;
});
// Summary component
const items = [];
app.addEventListener("cart:add", (e) => {
items.push(e.detail);
const total = items.reduce((sum, i) => sum + i.price, 0);
document.getElementById("summary").textContent = `${items.map((i) => i.title).join(" + ")} = ₹${total}`;
});
const [course, workbook] = document.querySelectorAll("#catalog button");
course.click();
workbook.click();
console.log("badge:", document.getElementById("badge").textContent);
console.log("summary:", document.getElementById("summary").textContent);
badge: 2 summary: JS Course + DOM Workbook = ₹798
Custom events decouple components: the catalog dispatches, any number of listeners react. bubbles: true lets the event reach #app, and detail carries the data.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!