@mr-samani/event-bus
Version:
A lightweight JavaScript event bus for any framework
160 lines (100 loc) โข 2.93 kB
Markdown
# @mr-samani/event-bus
A lightweight and dependency-free global event bus for JavaScript and TypeScript. Easily broadcast and listen to events across your appโno tight coupling, no headaches.
## ๐ Installation
```bash
npm install @mr-samani/event-bus
````
or with Yarn:
```bash
yarn add @mr-samani/event-bus
```
## ๐ง Features
โ
Zero dependencies
โ
Extremely lightweight (< 1 KB)
โ
Supports unlimited listeners
โ
Global `app.event` usage (no import needed)
โ
Works with TypeScript, JavaScript, Angular, React, Vue, Node, Electron
## ๐ง Usage
### ๐ฆ 1. Import and Use
```ts
import eventBus from '@mr-samani/event-bus';
// Listen to an event
eventBus.on('user:login', (user) => {
console.log('User logged in', user);
});
// Trigger the event
eventBus.trigger('user:login', { id: 1, name: 'Samani' });
```
### ๐ 2. Use Globally (No import needed!)
The event bus is also automatically attached to the global `app.event` object.
```ts
app.event.on('dashboard:loaded', () => console.log('Dashboard ready!'));
app.event.trigger('dashboard:loaded');
```
## โ๏ธ Framework Examples
### โก Angular
```ts
app.event.on('form:submit', (data) => {
console.log('Form submitted!', data);
});
```
> You can also inject it via a shared service and expose it to components.
### โ React
```js
useEffect(() => {
app.event.on('theme:change', handleThemeChange);
return () => app.event.off('theme:change');
}, []);
```
### ๐ Vue 3
```ts
mounted() {
app.event.on('cart:update', this.handleCart);
},
beforeUnmount() {
app.event.off('cart:update');
}
```
### ๐ป Node.js / Electron
```ts
app.event.trigger('system:booted');
```
Works seamlessly in CommonJS and ESM environments.
## ๐งช API Reference
| Method | Description |
| ------------------------ | --------------------------------------------- |
| `on(name, callback)` | Register a listener for an event |
| `off(name)` | Remove all listeners for the given event name |
| `trigger(name, ...args)` | Trigger the event with optional arguments |
## ๐ง TypeScript Support
Already comes with built-in types. If you use `window.app.event`, include this in your `tsconfig.json`:
```json
{
"compilerOptions": {
"types": ["@mr-samani/event-bus"]
}
}
```
Youโll get full autocompletion and type safety.
## ๐ค Example Use Cases
* App-wide loading states
* Modal open/close triggers
* Shared form submission
* Notification broadcasting
* Micro frontends messaging
## โ Author
Made with โค๏ธ by [Mohammadreza Samani](https://github.com/mr-samani)
## ๐ชช License
**ISC** โ Do anything you want.