Concept Explanation
Imagine a News Agency. They Publish stories to the wire. They don't know who is reading. Thousands of different newspapers (Subscribers) listen to the wire. Some only want "Sports," some only want "Politics."
In JS, this pattern lets you send messages between parts of your app that don't even know each other exists.
Syntax or Core Structure (Vanilla JS)
const bus = {
events: {},
subscribe(event, callback) {
if (!this.events[event]) this.events[event] = [];
this.events[event].push(callback);
},
publish(event, data) {
if (this.events[event]) {
this.events[event].forEach(cb => cb(data));
}
}
};
// Use it!
bus.subscribe("alert", (msg) => console.log("Alert: " + msg));
bus.publish("alert", "Something went wrong!");
Best Practices
- Unsubscribe: Always provide a way to "Stop listening" when a component is destroyed to prevent memory leaks.
- Specific Names: Use namespaces like
orders.createdinstead of justcreated. - Synchronous vs Asynchronous: Decide if the publisher should wait for all subscribers to finish or just "Fire and Forget."
Practice Exercises
- The Event Bus: Build the simple
busobject above from scratch. - The Multi-Subscriber: Subscribe two different functions to the same event. Publish the event once and ensure both functions run.
- The One-Timer: Add a
.once()method to your bus that automatically unsubscribes the callback after it runs once.