This class allows you to trigger and listen to events in JavaScript and TypeScript.
Install the latest stable version...
npm install --save @nestorrente/event-bus
... then import it in your modules:
import EventBus from '@nestorrente/event-bus';
You can download the latest version from here. Then, you can use it as any other JavaScript file:
<script src="event-bus.js"></script>
Or, if you prefer, you can use any of the following CDN repositories:
<!-- Unpkg -->
<script src="https://unpkg.com/@nestorrente/[email protected]"></script>
<!-- JsDelivr -->
<script src="https://cdn.jsdelivr.net/npm/@nestorrente/[email protected]"></script>
const eventBus = new EventBus();
eventBus.on('my-event', (param1, param2) => {
console.log(`Event received with params "${param1}" and "${param2}"`);
});
eventBus.trigger('my-event', 1, 'two');
// console will display:
// > Event received with params "1" and "two"
// You can also chain method calls
eventBus.on('my-event', () => { /* do nothing */ })
.trigger('my-event')
.off('my-event');
on(event: string, listener: (...args: any[]) => void): EventBus;
Registers an event listener function for the specified event.
Usage example:
eventBus.on('my-event', (param1, param2, /* ... more params... */) => {
// ... handle event...
});
off(event: string, listener?: (...args: any[]) => void): EventBus;
Unregisters an event listener for the specified event.
If listener
parameter is not specified, all event listeners registered for the specified event are unregistered.
Usage example:
// Define an event listener...
const myEventHandler = () => {
console.log('Event triggered');
};
// ... register it on the bus...
eventBus.on('my-event', myEventHandler);
// ... then remove it
eventBus.off('my-event', myEventHandler);
// This will remove all registered event listeners for 'my-event'
eventBus.off('my-event');
once(event: string, listener: (...args: any[]) => void): EventBus;
Registers an event listener function that will be called at most once for the specified event.
This method receives the same parameters as on()
.
Usage example:
eventBus.once('my-event', (param1, param2, /* ... more params... */) => {
// ... handle event...
});
trigger(event: string, ...eventParameters: any[]): EventBus;
Invokes all event listeners registered for the specified event. You can pass any number of parameters of any type.
Usage example:
// Without parameters
eventBus.trigger('my-event');
// With 4 parameters (number, boolean, string and array)
eventBus.trigger('my-event', 42, true, 'OMG', ['this', 'is', 'cool']);