Advertisement
PastebinhoLuisinho

Untitled

Jul 13th, 2023
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | Source Code | 0 0
  1. const Eventer = () => {
  2. let events = {}
  3.  
  4. const listen = (eventName, callback) => {
  5. try {
  6. if (!events[eventName]) {
  7. events[eventName] = {
  8. callbacks: [{ callbackFunction: callback }]
  9. }
  10. } else {
  11. events[eventName] = {
  12. callbacks: [...events[eventName].callbacks, { callbackFunction: callback }]
  13. }
  14. }
  15. } catch (err) { }
  16. }
  17.  
  18. const removeCallback = (eventName, callbackIndex) => {
  19. events[eventName].callbacks[callbackIndex] = events[eventName].callbacks.filter((cb, index) => index != callbackIndex)
  20. }
  21.  
  22. const emit = (eventName, data = {}) => {
  23. try {
  24. const callbackList = events[eventName]?.callbacks
  25. if (callbackList) {
  26. callbackList.forEach(({ callbackFunction, type }, index) => {
  27. if (type?.name === 'listenOnce') {
  28. callbackFunction(data)
  29. removeCallback(eventName, index)
  30. return
  31. }
  32. callbackFunction(data)
  33. })
  34. }
  35. } catch (err) { }
  36. }
  37.  
  38. const removeEvent = (eventNameToBeRemoved) => {
  39. const newEvents = Object.keys(events).reduce((updatedEvents, eventName) => {
  40. if (eventName !== eventNameToBeRemoved) {
  41. return { ...updatedEvents, [eventName]: events[eventName] }
  42. }
  43. return updatedEvents
  44. }, {})
  45.  
  46. events = newEvents
  47. }
  48.  
  49. const listenOnce = (eventName, callback) => {
  50. try {
  51. if (!events[eventName]) {
  52. events[eventName] = {
  53. callbacks: [{ callbackFunction: callback, type: { name: 'listenOnce' } }],
  54. }
  55. } else {
  56. events[eventName] = {
  57. callbacks: [...events[eventName]?.callbacks, { callbackFunction: callback, type: { name: 'listenOnce' } }]
  58. }
  59. }
  60. } catch (err) { }
  61. }
  62.  
  63. const removeAllEvents = () => {
  64. events = {}
  65. }
  66.  
  67. return {
  68. listen,
  69. emit,
  70. removeEvent,
  71. listenOnce,
  72. removeAllEvents
  73. }
  74. }
  75.  
  76. export const EventEmitter = Eventer()
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement