EventEmitter
class, which is part of the built-in events
module.What is the value of Object Oriented Programming used in tandem with Event Driven Programming?
Consider your knowledge of Event Driven Programming in the Web Browser, now explain to a non-technical friend how Event Driven Programming might be useful on the backend using Node.js.
1. Importing EventEmitter
const EventEmitter = require('events').EventEmitter;
2. Creating an instance of EventEmitter
const myEmitter = new EventEmitter;
3. Defining an Event Listener
Event listeners are functions that will be executed when a certain event is emitted. They can be added with .on(eventName, listenerFunction)
or .addListener(eventName, listenerFunction)
.
myEmitter.on('someEvent', function() {
console.log('someEvent occurred!');
});
4. Emitting an Event
Events can be emitted with .emit(eventName)
.
myEmitter.emit('someEvent'); // Logs 'someEvent occurred!' to the console
5. Removing a Listener
Event listeners can be removed with .removeListener(eventName, listenerFunction)
or .off(eventName, listenerFunction)
.
function eventResponse() {
console.log('someEvent occurred!');
}
myEmitter.on('someEvent', eventResponse);
myEmitter.removeListener('someEvent', eventResponse);
6. Removing All Listeners for an Event
All listeners for an event can be removed with .removeAllListeners([eventName])
. If no event name is provided, all listeners for all events are removed.
myEmitter.removeAllListeners('someEvent');
7. Listening for an Event Only Once
Listeners can be added that are triggered only once and then removed with .once(eventName, listenerFunction)
.
myEmitter.once('someEvent', function() {
console.log('someEvent occurred once!');
});
8. Getting the Count of Listeners for an Event
The number of listeners listening to a particular event can be retrieved with .listenerCount(eventName)
.
console.log(EventEmitter.listenerCount(myEmitter, 'someEvent'));
Remember to replace 'someEvent'
and eventResponse
with the names of your actual events and functions. These are just examples.
This should cover most of the common operations with EventEmitters
. For more in-depth information, you can refer to the Node.js EventEmitter documentation.