Created
May 7, 2022 12:06
-
-
Save leonardssh/0cf25a27bd1a9eeabd15a6e5d4237f11 to your computer and use it in GitHub Desktop.
Small Vue3 helper for communicating and debugging webviews. Also removes events when unmounted.
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
import { onUnmounted } from 'vue'; | |
const insideAltV = 'alt' in window; | |
export function useAltV(removeEventsOnUnmount: boolean = true) { | |
const eventHandlers: { [eventName: string]: Array<(...args: any[]) => Promise<void> | void> } = {}; | |
const instance = { | |
insideAltV, | |
on: (eventName: string, listener: (...args: any[]) => void): void => { | |
if (!insideAltV) { | |
console.log(`[alt:V] Adding Event Listener for event '${eventName}'`); | |
return; | |
} | |
alt.on(eventName, listener); | |
if (!eventHandlers[eventName]) eventHandlers[eventName] = []; | |
eventHandlers[eventName].push(listener); | |
}, | |
off: (eventName: string, listener: (...args: any[]) => void): void => { | |
if (!insideAltV) { | |
console.log(`[alt:V] Removing Event Listener for event '${eventName}'`); | |
return; | |
} | |
alt.off(eventName, listener); | |
if (eventHandlers[eventName]) { | |
const index = eventHandlers[eventName].findIndex(listener); | |
if (index > -1) eventHandlers[eventName].splice(index, 1); | |
if (!eventHandlers[eventName].length) delete eventHandlers[eventName]; | |
} | |
}, | |
emit: (eventName: string, ...args: any[]): void => { | |
if (!insideAltV) { | |
console.log(`[alt:V] Emitting event '${eventName}' with args: ${args}`); | |
return; | |
} | |
alt.emit(eventName, ...args); | |
}, | |
}; | |
if (removeEventsOnUnmount && insideAltV) { | |
onUnmounted(() => { | |
for (const eventName in eventHandlers) { | |
for (const listener of eventHandlers[eventName]) { | |
alt.off(eventName, listener); | |
} | |
delete eventHandlers[eventName]; | |
} | |
}); | |
} | |
return instance; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment