UNPKG

observer-pattern-js

Version:

Observer pattern implementation in js

66 lines (60 loc) 2.03 kB
/** * Create a new instances EventEmitter. * @class * @implements { IEventEmitter } */ export class EventEmitter { constructor() { /** * All subscriptions are stored in this object. * @private */ this.listeners = {}; } /** * Synchronously calls each of the listeners registered for the event named eventName. * @param { string } eventName. * @param { ...* } args - You can pass as many arguments as you like. * @public - This method is available to all instances of the EventEmitter class. * @throws Throws an error if no listener has been registered for an event named eventName. * @return { void } - This method returns nothing. */ emit(eventName, ...args) { if (!this.listeners[eventName]) { throw new Error(`this event "${eventName}" was not found.`); } this.listeners[eventName].forEach((listener) => { listener(...args); }); } /** * Adds the listener function to the end of the listeners array for the event named eventName. * @param { string } eventName - name of events to subscribe. * @param { IEmitterCallBack } cb - listener function. * @public - This method is available to all instances of the EventEmitter class. * @return { IEmitterSubscriber } - Will return the subscriber object. * method with which you can unsubscribe from an event. */ subscribe(eventName, cb) { if (this.listeners[eventName]) { this.listeners[eventName].push(cb); } else { this.listeners[eventName] = [cb]; } return { unsubscribe: () => { this.listeners[eventName] = this.listeners[eventName].filter( (listener) => listener !== cb ); }, }; } /** * This method returns a list of listeners. * @return {IListeners} - list of listeners. * @public - This method is available to all instances of the EventEmitter class. */ getListeners() { return this.listeners; } }