Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. function createEventEmitter<T>() {
  2. let listeners: ((action: T) => void)[] = [];
  3. return {
  4. subscribe,
  5. dispatch,
  6. };
  7.  
  8. function subscribe(listener: (action: T) => void) {
  9. listeners.push(listener);
  10. return function unsubscribe() {
  11. const idx = listeners.findIndex(f => f === listener);
  12. listeners.splice(idx, 1);
  13. };
  14. }
  15.  
  16. function dispatch(action: T) {
  17. listeners.forEach(f => f(action));
  18. return action;
  19. }
  20. }
  21.  
  22.  
  23. /* Demo */
  24.  
  25. interface Foo {
  26. type: 'FooAction';
  27. payload: number;
  28.  
  29. }
  30. interface Bar {
  31. type: 'BarAciton';
  32. payload: string;
  33. }
  34.  
  35. type ActionTypes = Foo | Bar;
  36.  
  37.  
  38. const ee = createEventEmitter<ActionTypes>();
  39.  
  40.  
  41. ee.subscribe((action) => {
  42. switch (action.type) {
  43. case 'FooAction':
  44. return action.payload;
  45. default:
  46. break;
  47. }
  48.  
  49. });
  50.  
  51. ee.dispatch({ type: 'FooAction', payload: 1 });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement