Utilizziamo i cookie per migliorare la tua esperienza sul sito
CodeWorlds

Event Bus i architektura aplikacji

Implementacja systemu komunikacji między komponentami za pomocą event bus.

Implementacja Event Bus

1class EventBus {
2  constructor() {
3    this.events = {};
4  }
5
6  // Rejestracja nasłuchiwacza
7  on(eventName, callback) {
8    if (!this.events[eventName]) {
9      this.events[eventName] = [];
10    }
11    this.events[eventName].push(callback);
12
13    // Zwróć funkcję do usunięcia listenera
14    return () => this.off(eventName, callback);
15  }
16
17  // Usunięcie nasłuchiwacza
18  off(eventName, callback) {
19    if (this.events[eventName]) {
20      this.events[eventName] = this.events[eventName].filter(cb => cb !== callback);
21    }
22  }
23
24  // Jednorazowy nasłuchiwacz
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  // Emisja wydarzenia
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  // Usunięcie wszystkich listenerów dla wydarzenia
47  removeAllListeners(eventName) {
48    if (eventName) {
49      delete this.events[eventName];
50    } else {
51      this.events = {};
52    }
53  }
54}
55
56// Globalna instancja event bus
57const eventBus = new EventBus();
58
59// Użycie w różnych modułach aplikacji
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});
Vai a CodeWorlds