Categories
interview

Event Emitter pattern

Event emitter pattern implemented using a Javascript ES6 class.

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

  subscribe = (event, cb) => {
    (this.events[event] || (this.events[event] = [])).push(cb);
    return {
      unsubscribe: () => {
        (this.events[event] && this.events[event]).splice(this.events[event].indexOf(cb) >>> 0, 1);
      }
    };
  };

  emit = (event, ...rest) => {
    (this.events[event] || []).forEach(val => {
      val(...rest);
    });
  };
}

const eventEmitter = new EventEmitter();
const ret1 = eventEmitter.subscribe('test', () => {
  console.log('test1');
});
const ret2 = eventEmitter.subscribe('test', () => {
  console.log('test2');
});
const ret3 = eventEmitter.subscribe('test3', () => {
  console.log('test3');
});
t.emit('test'); // test1, test2
ret1.unsubscribe();
ret1.unsubscribe(); // Should still function as expected.
t.emit('test'); // test2

Demo