PubSub in 150 bytes

hassan shaikley
1 min readDec 8, 2023

--

One of my personal goals is to write a JS13K game so I am interested in ruthless optimization.

Pubsub is a pattern I really like but I have to be careful when pulling in dependencies that are too big. In the context of a 13K game that means almost any dependency.

Here’s how I implement pubsub in 183 bytes:

const eventTarget = new EventTarget();

export const subscribe = (eventName, callback) => {
eventTarget.addEventListener(eventName, callback);
return () => {
eventTarget.removeEventListener(eventName, callback);
};
};

export const publish = (n, data) => {
eventTarget.dispatchEvent(new CustomEvent(n, { detail: data }));
};

Which can be used in the following way:

const unsubscribe = subscribe('some event', e => {
console.log(e.detail);
});

publish('some event', { hello: 'world' });
// logs {hello: 'world'}
unsubscribe()
publish('some event', 123);
// does nothing

It can be taken even further to 151 bytes:

let t = new EventTarget();

export default {
sub: (e, c) => (t.addEventListener(e, c), _ => t.removeEventListener(e, c)),
pub: (n, d) => t.dispatchEvent(new CustomEvent(n, { detail: d })),
};

For comparison pubsub-js is 3kb compressed and minified. If used it would take up 25% of my game as opposed to 1%.

Sometimes you might need more features, if you do use a library like pubsub-js. But often times publish and subscribe are all you actually use.

--

--

hassan shaikley
hassan shaikley

No responses yet