Guest User

Untitled

a guest
Aug 19th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. /**
  2. * This class will notify all listeners any time any event get's fired.
  3. * @example
  4. * let dispatcher = new Dispatcher();
  5. * dispatcher.subscribe(callback);
  6. * dispatcher.dispatch({ type : 'myEvent', payload : 'hello' });
  7. *
  8. * @class Dispatcher
  9. */
  10. class Dispatcher {
  11. constructor() {
  12. this.listeners = [];
  13. }
  14.  
  15. /**
  16. * Add a listener for all events
  17. * @param {function} callback
  18. */
  19. subscribe(callback) {
  20. this.listeners.push(callback);
  21. }
  22.  
  23. /**
  24. * Remove a listener.
  25. * @param {function} callback
  26. */
  27. unsubscribe(callback) {
  28. this.listeners = this.listeners.filter(listener => listener !== callback);
  29. }
  30.  
  31. /**
  32. * Dispatch an event to notify listeners.
  33. * @param {object} event - the event with a payload to emit
  34. */
  35. dispatch(event) {
  36. this.listeners.forEach((callback) => {
  37. callback(event);
  38. });
  39. }
  40. }
  41.  
  42. export default Dispatcher;
Add Comment
Please, Sign In to add comment