UNPKG

@mr-samani/event-bus

Version:

A lightweight JavaScript event bus for any framework

160 lines (100 loc) โ€ข 2.93 kB
# @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.