als-event-emitter
is a lightweight, powerful implementation of an event emitter system, designed to be easy to use and extendable. It provides the ability to listen for and emit events in a Node.js environment.
Install using npm:
npm install als-event-emitter
Import als-event-emitter
in your Node.js project and create an instance of EventEmitter
:
const EventEmitter = require('als-event-emitter');
const emitter = new EventEmitter();
If you want to include the script in a browser without using any module system, you can use the event-emitter.js:
Place the event-emitter.js in a directory that your browser can access.
In your HTML:
<script src="./node_modules/als-event-emitter/emitter.js"></script>
<script>
// After the script has been loaded, EventEmitter will be available as a global variable
const myEmitter = new EventEmitter();
</script>
Registers a listener for the specified event.
-
eventName
(String): Name of the event. -
listener
(Function): Callback function.
Registers a one-time listener for the specified event.
-
eventName
(String): Name of the event. -
listener
(Function): Callback function.
Removes all listeners for the specified event.
-
eventName
(String): Name of the event.
Removes the specified listener from all events.
-
listener
(Function): Callback function to be removed.
Removes all registered listeners for all events.
Emits the specified event with optional arguments.
-
eventName
(String): Name of the event. -
...args
: Arguments to pass to the event listeners.
Registers a listener that will be triggered for any emitted event, even if event not exists.
-
listener
(Function): Callback function. -
once
(Boolean): If true, the listener will be triggered only once.
Registers a one-time listener for any emitted event, even if event not exists.
-
listener
(Function): Callback function.
Checks if there are any listeners registered for the specified event.
-
eventName
(String): Name of the event.
const emitter = new EventEmitter();
emitter.on('data', (data) => {
console.log(`Received data: ${data}`);
});
emitter.emit('data', 'Hello World');
emitter.once('init', () => {
console.log('Initialization event');
});
emitter.emit('init');
emitter.emit('init'); // This won't trigger the callback again.
const callback = (data) => {
console.log(`Received: ${data}`);
};
emitter.on('data', callback);
emitter.removeListener(callback);
emitter.emit('data', 'This will not be logged');