Comment

Comment by arnorhs

I'm not a huge fan of using CustomEvent for this.. esp. in terms of interoperability (which for these <kb challenges probably doesnt matter)

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()
parent arnorhs 1 year ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton