Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create custom event listener in node.js (express.js)?

Tags:

node.js

events

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.

like image 609
murvinlai Avatar asked Apr 21 '11 01:04

murvinlai


People also ask

How do I create a custom event listener?

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.

What are event listeners in node JS?

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.

What JavaScript method do we use to create an event listener?

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.


2 Answers

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.

like image 149
StephaneP Avatar answered Oct 07 '22 00:10

StephaneP


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');
like image 29
kavigun Avatar answered Oct 07 '22 01:10

kavigun