Implementing a communication system between components using an event bus.
1class EventBus {
2 constructor() {
3 this.events = {};
4 }
5
6 // Register a listener
7 on(eventName, callback) {
8 if (!this.events[eventName]) {
9 this.events[eventName] = [];
10 }
11 this.events[eventName].push(callback);
12
13 // Return a function to remove the listener
14 return () => this.off(eventName, callback);
15 }
16
17 // Remove a listener
18 off(eventName, callback) {
19 if (this.events[eventName]) {
20 this.events[eventName] = this.events[eventName].filter(cb => cb !== callback);
21 }
22 }
23
24 // One-time listener
25 once(eventName, callback) {
26 const onceCallback = (...args) => {
27 callback(...args);
28 this.off(eventName, onceCallback);
29 };
30 this.on(eventName, onceCallback);
31 }
32
33 // Emit an event
34 emit(eventName, ...args) {
35 if (this.events[eventName]) {
36 this.events[eventName].forEach(callback => {
37 try {
38 callback(...args);
39 } catch (error) {
40 console.error(`Error in event listener for ${eventName}:`, error);
41 }
42 });
43 }
44 }
45
46 // Remove all listeners for an event
47 removeAllListeners(eventName) {
48 if (eventName) {
49 delete this.events[eventName];
50 } else {
51 this.events = {};
52 }
53 }
54}
55
56// Global event bus instance
57const eventBus = new EventBus();
58
59// Usage in different application modules
60// Module A
61eventBus.on('dinosaurEscape', (dinosaurData) => {
62 showEmergencyAlert(dinosaurData);
63});
64
65// Module B
66function handleDinosaurEscape(dinosaur) {
67 eventBus.emit('dinosaurEscape', {
68 id: dinosaur.id,
69 name: dinosaur.name,
70 location: dinosaur.enclosure,
71 dangerLevel: dinosaur.dangerLevel
72 });
73}
74
75// Module C
76eventBus.on('dinosaurEscape', (dinosaurData) => {
77 if (dinosaurData.dangerLevel > 8) {
78 activateEmergencyProtocols();
79 }
80});