Last active
December 28, 2021 11:28
-
-
Save daaru00/450717046b917f0d44555e2a867580ee to your computer and use it in GitHub Desktop.
Vue 3 composition API events bus implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const eventBus = new Comment('global-event-bus'); | |
const listeners = {}; | |
export const EVENT_NAME = 'MyEventName'; | |
export default function () { | |
/** | |
* @param {string} event | |
* @param {function} callback | |
* @returns {number} index | |
*/ | |
const on = (event, callback) => { | |
const index = new Date().getTime(); | |
listeners[index] = { | |
listener: ({ detail }) => { | |
callback(detail); | |
}, | |
event, | |
}; | |
eventBus.addEventListener(event, listeners[index].listener); | |
return index; | |
}; | |
/** | |
* @param {number} index | |
*/ | |
const off = (index) => { | |
const listener = listeners[index]; | |
if (!listener) { | |
return; | |
} | |
eventBus.removeEventListener(listener.event, listener.listener); | |
delete listeners[index]; | |
}; | |
/** | |
* @param {string} event | |
* @param {object} data | |
*/ | |
const emit = (event, data) => { | |
eventBus.dispatchEvent( | |
new CustomEvent(event, { | |
detail: data, | |
}) | |
); | |
}; | |
return { | |
on, | |
off, | |
emit, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment