I have a giant function with a lot of nested callbacks. I want to make it cleaner and easier to handle. So, I'm thinking of using custom event listeners
Like, when a function is done, in the callback, instead of putting a chunk of code, it just emits an event, and then the listener will run.
So, how to do that in node.js? I am still looking for a good example to guide me through.
To listen for the custom event, add an event listener to the element you want to listen on, just as you would with native DOM events. document. querySelector("#someElement"). addEventListener("myevent", (event) => { console.
once(event, listener)Adds a one time listener to the event. This listener is invoked only the next time the event is fired, after which it is removed. Returns emitter, so calls can be chained.
The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.
You can set events like this
app.on('event:user_created', callback);
Then you can emit them
app.emit('event:user_created', data);
express.js uses EventEmitter
.
The Node.js "events" module and the "EventEmitter" module facilitates communication between objects in Node. The EventEmitter module is at the core of Node's asynchronous event-driven architecture. Here is how you can create custom events and emit them:
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
//Event Listener
const EventListenerFunc = () => {
console.log('an event occurred!');
}
//Registering the event with the listener
myEmitter.on('eventName', EventListenerFunc);
//Emitting the event
myEmitter.emit('eventName');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With