如何在 node.js (express.js) 中创建自定义事件监听器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5738552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:03:41  来源:igfitidea点击:

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

eventsnode.js

提问by murvinlai

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.

那么,如何在 node.js 中做到这一点?我仍在寻找一个很好的例子来指导我。

采纳答案by mjs

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

您可能想要创建一个EventEmitter对象,并调用emit()它。

回答by StephaneP

You can set events like this

您可以设置这样的事件

app.on('event:user_created', callback);

Then you can emit them

然后你可以发出它们

app.emit('event:user_created', data);

express.jsuses EventEmitter.

express.js使用EventEmitter.

回答by Olumuyiwa akin-ogundeji

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

我刚刚遇到这个问题,我想投入 2 美分,专门回答路易斯。

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

在 Express 中,如果您希望 'app' 实例侦听自定义事件,您可以执行以下操作:

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.

然后当该路由被命中时,您会在控制台中看到响应。当然,您可以根据需要实现它。