11

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.

Wayne
  • 59,728
  • 15
  • 131
  • 126
murvinlai
  • 48,919
  • 52
  • 129
  • 177

4 Answers4

29

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.

bluish
  • 26,356
  • 27
  • 122
  • 180
StephaneP
  • 407
  • 4
  • 3
9

You probably want to create an EventEmitter object, and call emit() on it.

mjs
  • 63,493
  • 27
  • 91
  • 122
6

I just came across this question, I'd like to chip in my 2 cents, specifically responding to Luis.

In Express, if you want the 'app' instance to listen for a custom event you would do something like:

app.on('testEvent', function () {
  return console.log('responded to testEvent');
});

app.get('/test', function (req, res) {
  app.emit('testEvent');
  return res.status(200).end();
});

Then when that route is hit, you'd see the response in the console. Of course you can implement this as you wish.

Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41
1

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');
kavigun
  • 2,219
  • 2
  • 14
  • 33