Created
February 13, 2024 09:05
-
-
Save alexpilugin/ef36f94f61038472d8295e3541d7f63e to your computer and use it in GitHub Desktop.
(Vue 3 Composables) JavaScript version of EventBus from a developit/mitt TypeScript library
This file contains 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
// JavaScript Version of: https://raw.githubusercontent.com/developit/mitt/main/src/index.ts | |
// Define the event bus outside of the exported function to ensure a singleton | |
const all = new Map(); | |
const on = (type, handler) => { | |
const handlers = all.get(type) || []; | |
all.set(type, [...handlers, handler]); | |
}; | |
const off = (type, handler) => { | |
const handlers = all.get(type) || []; | |
if (handler) { | |
const index = handlers.indexOf(handler); | |
if (index > -1) { | |
handlers.splice(index, 1); | |
all.set(type, handlers); | |
} | |
} else { | |
all.delete(type); | |
} | |
}; | |
const emit = (type, evt) => { | |
const handlers = all.get(type) || []; | |
handlers.forEach(handler => handler(evt)); | |
// Handle wildcard '*' event listeners if any | |
const wildcardHandlers = all.get('*') || []; | |
wildcardHandlers.forEach(handler => handler(type, evt)); | |
}; | |
// The exported function always returns the same instance of the event bus methods | |
export const useEventBus = () => ({ on, off, emit }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment