Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * This class will notify all listeners any time any event get's fired.
- * @example
- * let dispatcher = new Dispatcher();
- * dispatcher.subscribe(callback);
- * dispatcher.dispatch({ type : 'myEvent', payload : 'hello' });
- *
- * @class Dispatcher
- */
- class Dispatcher {
- constructor() {
- this.listeners = [];
- }
- /**
- * Add a listener for all events
- * @param {function} callback
- */
- subscribe(callback) {
- this.listeners.push(callback);
- }
- /**
- * Remove a listener.
- * @param {function} callback
- */
- unsubscribe(callback) {
- this.listeners = this.listeners.filter(listener => listener !== callback);
- }
- /**
- * Dispatch an event to notify listeners.
- * @param {object} event - the event with a payload to emit
- */
- dispatch(event) {
- this.listeners.forEach((callback) => {
- callback(event);
- });
- }
- }
- export default Dispatcher;
Add Comment
Please, Sign In to add comment