A simple, no-dependency, synchronous event bus written in TypeScript
# NPM
npm i --save @sylvmty/simple-event-bus
# PNPM
pnpm add --save @sylvmty/simple-event-bus
# Yarn
yarn add @sylvmty/simple-event-bus
- Native TypeScript support
- No dependencies
- Synchronous event bus
- Event handlers with priority (sorted execution)
- Easy to use
- Lightweight: 0.88 kB (0.39 kB with gzip)
- Compiled in ESM, CJS, UMD for convenience
- NestJS native package
I decided to create my own library after using EventEmitter2 for some time in my projects.
I found it too complex for my needs and it was also lacking some features like prioritized event handlers.
import { EventBus } from "@sylvmty/simple-event-bus"
const eventBus = new EventBus()
eventBus.on("myEvent", (message: string, eventName: string) => {
console.log("Handler 1:", message, `(event name: ${eventName})`)
})
// Also works with async handlers (they will still be executed sequentially)
eventBus.on("myEvent", async (message: string, eventName: string) => {
console.log("Handler 2:", message, `(event name: ${eventName})`)
})
await await eventBus.emit("myEvent", "This is a message")
// Output:
// Handler 1: This is a message (event name: myEvent)
// Handler 2: This is a message (event name: myEvent)
If you have an idea for an improvement, feel free to fork this repository and submit a PR!
- Node.js LTS (you can use nvm to manage Node versions)
- pnpm (
npm install -g pnpm
)
pnpm install
The template contains the following pnpm
scripts:
dev
- Start the file watcher (will recompile the code on source file change)build
- Build for productionlint
- Checks your code for any linting errorstest
- Run all teststest:watch
- Run all tests with watch modetest:coverage
- Run all tests with code coverage report
This repository under the MIT License, feel free to use it and modify it.