Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const Eventer = () => {
- let events = {}
- const listen = (eventName, callback) => {
- try {
- if (!events[eventName]) {
- events[eventName] = {
- callbacks: [{ callbackFunction: callback }]
- }
- } else {
- events[eventName] = {
- callbacks: [...events[eventName].callbacks, { callbackFunction: callback }]
- }
- }
- } catch (err) { }
- }
- const removeCallback = (eventName, callbackIndex) => {
- events[eventName].callbacks[callbackIndex] = events[eventName].callbacks.filter((cb, index) => index != callbackIndex)
- }
- const emit = (eventName, data = {}) => {
- try {
- const callbackList = events[eventName]?.callbacks
- if (callbackList) {
- callbackList.forEach(({ callbackFunction, type }, index) => {
- if (type?.name === 'listenOnce') {
- callbackFunction(data)
- removeCallback(eventName, index)
- return
- }
- callbackFunction(data)
- })
- }
- } catch (err) { }
- }
- const removeEvent = (eventNameToBeRemoved) => {
- const newEvents = Object.keys(events).reduce((updatedEvents, eventName) => {
- if (eventName !== eventNameToBeRemoved) {
- return { ...updatedEvents, [eventName]: events[eventName] }
- }
- return updatedEvents
- }, {})
- events = newEvents
- }
- const listenOnce = (eventName, callback) => {
- try {
- if (!events[eventName]) {
- events[eventName] = {
- callbacks: [{ callbackFunction: callback, type: { name: 'listenOnce' } }],
- }
- } else {
- events[eventName] = {
- callbacks: [...events[eventName]?.callbacks, { callbackFunction: callback, type: { name: 'listenOnce' } }]
- }
- }
- } catch (err) { }
- }
- const removeAllEvents = () => {
- events = {}
- }
- return {
- listen,
- emit,
- removeEvent,
- listenOnce,
- removeAllEvents
- }
- }
- export const EventEmitter = Eventer()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement