mitt
🥊 Tiny 200 byte functional event emitter / pubsub.
A tiny JavaScript event emitter under 200 bytes that lets separate parts of your app send and receive messages without being directly connected, with full TypeScript support for catching type mistakes at compile time.
Mitt is a JavaScript utility that lets different parts of a program send messages to each other without needing to be directly connected. This pattern is called an event emitter or publish-subscribe. One piece of code says "something happened" by emitting an event, and other pieces of code that registered interest in that event get notified and can respond. This is a very common need in web applications, and mitt is an extremely small solution to it, under 200 bytes in size when compressed.
The API has three main operations. You call on to register a handler function for a named event, emit to fire an event and pass along any data, and off to stop listening. There is also a special wildcard event name using an asterisk that lets a single handler receive every event regardless of its name, which can be useful for debugging or logging. All registered handlers are stored in a plain Map object, which you can also clear directly.
Mitt works in both browsers and server-side JavaScript environments. It has no dependencies. The README notes it supports Internet Explorer 9 and later in addition to modern browsers.
For TypeScript users, mitt supports defining the full set of events and their data types upfront, so the type checker can catch mistakes like emitting a string where a number was expected or listening for an event name that was never defined.
Installation is through npm. The package can also be loaded directly in a web page via a script tag without any build step. The project is open-source under the MIT license.
Where it fits
- Add a lightweight publish-subscribe message bus to a JavaScript or TypeScript app so components can communicate without importing each other directly.
- Use the wildcard event handler to log every event in your app for debugging without changing any emitting code.
- Replace a heavy event library with mitt in a bundle-size-sensitive web app since the entire library compresses to under 200 bytes.