The smallest PubSub library possible. Zero Dependencies. 149 bytes.
I wrote this article a while back. But I realized…why not just publish the code?
Smaller than the competition.
Built with JS13K games in mind. Such as cred which is unfortunately in need of some weight loss soon, it is almost 25KB now.
If you have any ideas that may trim off even one single byte please share it. Create an issue! I don’t mind.
This is the entire source (index.js).
unsub()
pub(‘jump’, “another_user_id”)
>> Nothing happens now” dir=”auto”>
import "pico-pubsub" const unsub = sub('jump', function (anything) { console.log("someone jumped - " + anything.detail) }); pub('jump', "a_user_id") >> "someone jumped - a_user_id" unsub() pub('jump', "another_user_id") >> Nothing happens now
- Might add TS support in the future. For now you can use the following snippet.
The following command will produce a 149b
file:
npx esbuild index.js --bundle --minify --format=esm --outfile=bundle.js
Coming in at #2 we have nano-pubsub which slims down to an impressive 194b
…Not bad at all! Only ~30%
larger.
14 Comments
lerp-io
should this copy paste macro even be a package lol
est
TIL CustomEvent
https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent…
RazorDev
[flagged]
pjc50
This is local pubsub within an application, right? i.e. corresponding to C#'s 'event' keyword.
nsonha
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.
h1fra
sure if you remove the whole native package it's small
blatantly
23 byte version:
test1072
Perhaps "eventlistener" word can be extracted, and dynamically called as string to reduce bytes
sltkr
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).
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:
giancarlostoro
So why would I use this as opposed to BroadcastChannel?
tipiirai
Thanks! Definitely going to use `new EventTarget()` in Nue. So obvious.
https://nuejs.org/
zeroq
In similar spirit, a minimal implemention of KV store, in 22 bytes:
curtisszmania
[dead]