jsartisan / frontend-challenges

FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
https://frontend-challenges.com
20 stars 3 forks source link

58 - Event Emitter - javascript #60

Open jsartisan opened 1 month ago

jsartisan commented 1 month ago

index.js

export class EventEmitter {
  constructor() {
    this.callbacks = [];
  }

  on(eventName, callback) {
    if (eventName in this.callbacks) {
      this.callbacks[eventName].push(callback);

      return;
    }

    this.callbacks[eventName] = [callback];
  }

  emit(eventName, ...args) {
    if (eventName in this.callbacks) {
      this.callbacks[eventName].forEach((listener) => {
        listener(...args);
      });
    }
  }

  off(eventName, callback) {
    if (eventName in this.callbacks) {
      const index = this.callbacks[eventName].indexOf(callback);

      if (index > -1) {
        this.callbacks[eventName].splice(index, 1);
      }
    }
  }
}