Created
November 7, 2021 16:26
-
-
Save GoodNovember/e610aaa82499198ab50e8879dc635818 to your computer and use it in GitHub Desktop.
My take on the Signal event concept
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
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