Advertisement
Anatolyukropov

EventManager

Dec 11th, 2024
6
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. interface EventListener {
  2. handleEvent(eventName: string, data: any): void;
  3. }
  4.  
  5. class LoggerListener implements EventListener {
  6. handleEvent(eventName: string, data: any): void {
  7. console.log(`Logger: Event "${eventName}" occurred with data:`, data);
  8. }
  9. }
  10.  
  11. class AnalyticsListener implements EventListener {
  12. handleEvent(eventName: string, data: any): void {
  13. console.log(`Analytics: Captured event "${eventName}" with data:`, data);
  14. }
  15. }
  16.  
  17. class EventManager {
  18. private listeners: EventListener[] = [];
  19.  
  20. addListener(listener: EventListener): void {
  21. this.listeners.push(listener);
  22. }
  23.  
  24. triggerEvent(eventName: string, data: any): void {
  25. this.listeners.forEach((listener) => listener.handleEvent(eventName, data));
  26. }
  27. }
  28.  
  29. // Пример использования
  30. const eventManager = new EventManager();
  31. eventManager.addListener(new LoggerListener());
  32. eventManager.addListener(new AnalyticsListener());
  33.  
  34. eventManager.triggerEvent("user_login", { userId: 123 });
  35. // Logger: Event "user_login" occurred with data: { userId: 123 }
  36. // Analytics: Captured event "user_login" with data: { userId: 123 }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement