Categories
interview

Event Emitter pattern

Event emitter pattern implemented using a Javascript ES6 class.

class EventEmitter {
  events = {};

  subscribe = (event, cb) => {
    (this.events[event] || (this.events[event] = [])).push(cb);
    return {
      unsubscribe: () => {
        const arr = this.events[event];
        (arr.length && arr.splice(arr.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');
});
eventEmitter.emit('test'); // test1, test2
ret1.unsubscribe();
ret1.unsubscribe(); // Should still function as expected.
eventEmitter.emit('test'); // test2

Demo