开发者

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

开发者 https://www.devze.com 2023-02-27 05:42 出处:网络
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

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.


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.


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


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.


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');
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号