Advertisement
Guest User

Untitled

a guest
Jun 27th, 2017
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. /* eslint-env browser */
  2.  
  3. const subscribtions = {};
  4. const listeners = {};
  5.  
  6. function subscribe(type) {
  7. const subscribers = [];
  8. subscribtions[type] = subscribers;
  9. const listener = event => {
  10. for (let i = 0; i < subscribers.length; i++) {
  11. subscribers[i](event);
  12. }
  13. };
  14. listeners[type] = listener;
  15. window.addEventListener(type, listener);
  16. }
  17.  
  18. function addEventListener(type, cb) {
  19. if (!type || typeof type !== 'string') {
  20. throw new Error('addEventListener type parameter must be non empty string.');
  21. }
  22. if (typeof cb !== 'function') {
  23. throw new Error('addEventListener listener parameter must be a function.');
  24. }
  25.  
  26. if (!subscribtions.hasOwnProperty(type) || !Array.isArray(subscribtions[type])) {
  27. subscribe(type);
  28. }
  29.  
  30. subscribtions[type].push(cb);
  31. }
  32.  
  33. function removeEventListener(type, listener) {
  34. if (!type || typeof type !== 'string') {
  35. throw new Error('removeEventListener type parameter must be non empty string.');
  36. }
  37. if (typeof cb !== 'function') {
  38. throw new Error('removeEventListener listener parameter must be a function.');
  39. }
  40.  
  41. if (subscribtions.hasOwnProperty(type)) {
  42. const subscribers = subscribtions[type];
  43. const index = subscribers.findIndex(x => x === listener);
  44. subscribers.splice(index, 1);
  45. if (subscribers.length === 0) {
  46. window.removeEventListener(type, listeners[type]);
  47. delete subscribtions[type];
  48. delete listeners[type];
  49. }
  50. }
  51. }
  52.  
  53. export default { addEventListener, removeEventListener };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement