79344456

Date: 2025-01-10 02:24:37
Score: 1.5
Natty:
Report link

@varaprasadh approach helped me get started, but lacked accumulating multiple events. Modified to also allow remove listener that functions similar to on DOM events to get rid of one based on callback.

class Dog {
  constructor() {
    this.listeners = {};
  }

  emit(method, payload = null) {
    if (this.listeners.hasOwnProperty(method)) {
      const callbacks = this.listeners[method];
      for (let [key, callback] of Object.entries(callbacks)) {
        if (typeof callback === 'function') {
          callback(payload);
        }
      }
    }
  }

  addEventListener(method, callback) {
    if (!this.listeners.hasOwnProperty(method)) {
      this.listeners[method] = {}
    }
    this.listeners[method][callback] = callback;
  }

  removeEventListener(method, callback) {
    if (this.listeners.hasOwnProperty(method)) {
      delete this.listeners[method][callback];
    }
  }
}

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @varaprasadh
  • Looks like a comment (1):
  • Low reputation (0.5):
Posted by: programmingisphun