logoalt Hacker News

Show HN: JavaScript PubSub in 163 Bytes

104 pointsby hmmokidk03/31/202536 commentsview on HN

Comments

sltkr04/01/2025

The API feels wrong. The object that was passed to pub() is the object that should be received by the callback passed to sub().

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).

show 3 replies
zeroq04/01/2025

In similar spirit, a minimal implemention of KV store, in 22 bytes:

  export default new Map
arnorhs04/01/2025

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()
show 4 replies
test107204/01/2025

Perhaps "eventlistener" word can be extracted, and dynamically called as string to reduce bytes

show 4 replies
giancarlostoro04/01/2025

So why would I use this as opposed to BroadcastChannel?

show 1 reply
thewisenerd04/01/2025

good to know pub-sub shenanigans are ubiquitous lol

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...

show 1 reply
nsonha04/01/2025

is this like left-pad but for EventTarget? If being small is the PRIMARY goal, then we are already able to do it without a wrapper.

show 2 replies
pjc5004/01/2025

This is local pubsub within an application, right? i.e. corresponding to C#'s 'event' keyword.

show 1 reply
h1fra04/01/2025

sure if you remove the whole native package it's small

lerp-io03/31/2025

should this copy paste macro even be a package lol

show 2 replies
curtisszmania04/01/2025

[dead]

RazorDev04/01/2025

[flagged]

show 1 reply
tipiirai04/01/2025

Thanks! Definitely going to use `new EventTarget()` in Nue. So obvious.

https://nuejs.org/

blatantly04/01/2025

23 byte version:

    // Lib code>>
    s={};call=(n)=>{s[n]()}
    // <<

    s.hello=()=>console.log('hello');
    call('hello');
    delete s.hello;
show 1 reply