Sobes.tech
Middle

Implement a class following the Observer / Event Emitter pattern: storing subscribers, subscribing to an event, unsubscribing from an event, notifying subscribers.

sobes.tech AI

Answer from AI

Below is an example implementation of the Observer pattern in JavaScript, which stores subscribers, allows subscribing, unsubscribing, and notifying them:

class EventEmitter {
  constructor() {
    this.subscribers = {};
  }

  // Subscribe to an event
  on(event, callback) {
    if (!this.subscribers[event]) {
      this.subscribers[event] = [];
    }
    this.subscribers[event].push(callback);
  }

  // Unsubscribe from an event
  off(event, callback) {
    if (!this.subscribers[event]) return;
    this.subscribers[event] = this.subscribers[event].filter(cb => cb !== callback);
  }

  // Notify subscribers
  emit(event, data) {
    if (!this.subscribers[event]) return;
    this.subscribers[event].forEach(callback => callback(data));
  }
}

// Example usage:
const emitter = new EventEmitter();

function onOrderStatusChange(status) {
  console.log('Order status changed to:', status);
}

emitter.on('orderStatus', onOrderStatusChange);
emitter.emit('orderStatus', 'Completed');
emitter.off('orderStatus', onOrderStatusChange);

This class allows flexible management of subscriptions and notifications.