by hmmokidk on 3/31/25, 1:37 AM with 36 comments
by sltkr on 4/1/25, 10:39 AM
The use of EventTarget/CustomEvent is an implementation detail; it should not be part of the API.
As a result, every callback implementation is larger because it must explicitly unwrap the CustomEvent object.
Essentially, the author made the library smaller by pushing necessary code to unwrap the CustomEvent object to the callsites. That's the opposite of what good libraries do!
The mentioned nano-pubsub gets this right, and it even gets the types correct (which the posted code doesn't even try).
by zeroq on 4/1/25, 3:42 PM
export default new Map
by arnorhs on 4/1/25, 11:53 AM
personally, i'll just roll with something like this which also is typed etc:
export function createPubSub<T extends readonly any[]>() {
const l = new Set<(...args: T) => void>()
return {
pub: (...args: T) => l.forEach((f) => f(...args)),
sub: (f: (...args: T) => void) => l.add(f) && (() => l.delete(f)),
}
}
// usage:
const greetings = createPubSub<[string]>()
const unsubscribe = greetings.sub((name) => {
console.log('hi there', name)
})
greetings.pub('Dudeman')
unsubscribe()
by est on 4/1/25, 8:31 AM
by test1072 on 4/1/25, 10:26 AM
by giancarlostoro on 4/1/25, 1:56 PM
by thewisenerd on 4/1/25, 7:05 PM
here's my implementation from a while back with `setTimeout` like semantics; used it to avoid prop-drilling in an internal dashboard (sue me)
https://gist.github.com/thewisenerd/768db2a0046ca716e28ff14b...
by nsonha on 4/1/25, 9:12 AM
by pjc50 on 4/1/25, 8:57 AM
by h1fra on 4/1/25, 9:16 AM
by lerp-io on 3/31/25, 8:19 AM
by tipiirai on 4/1/25, 2:18 PM
by blatantly on 4/1/25, 9:49 AM
// Lib code>>
s={};call=(n)=>{s[n]()}
// <<
s.hello=()=>console.log('hello');
call('hello');
delete s.hello;