Skip to content

Instantly share code, notes, and snippets.

@GoodNovember
Created November 7, 2021 16:26
Show Gist options
  • Save GoodNovember/e610aaa82499198ab50e8879dc635818 to your computer and use it in GitHub Desktop.
Save GoodNovember/e610aaa82499198ab50e8879dc635818 to your computer and use it in GitHub Desktop.
My take on the Signal event concept
export const makeSignal = () => {
const subscriptions = new Map()
const signal = {
get size () {
return subscriptions.size
},
subscribe (listenerFn) {
if (subscriptions.has(listenerFn) === false) {
if (typeof listenerFn === 'function') {
const pkg = {
isOnce: false,
listenerFn
}
subscriptions.set(listenerFn, pkg)
} else {
console.error('ERROR: Subscribe requires a function as a paramater.')
}
}
return () => {
if (subscriptions.has(listenerFn)) {
subscriptions.delete(listenerFn)
}
}
},
subscribeOnce (listenerFn) {
if (subscriptions.has(listenerFn) === false) {
if (typeof listenerFn === 'function') {
const pkg = {
isOnce: true,
listenerFn
}
subscriptions.set(listenerFn, pkg)
} else {
console.error('ERROR: SubscribeOnce requires a function as a paramater.')
}
}
return () => {
if (subscriptions.has(listenerFn)) {
subscriptions.delete(listenerFn)
}
}
},
emit (...props) {
for (const subscriber of subscriptions.values()) {
const { isOnce, listenerFn } = subscriber
listenerFn(...props)
if (isOnce) {
subscriptions.delete(listenerFn)
}
}
},
clear () {
subscriptions.clear()
}
}
return signal
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment