简体   繁体   English

什么时候在 Node js 中使用 eventEmitter?

[英]When to use eventEmitter in Node js?

I am learning new concept in node js that is event but i could not find where i should use this,I want any real scenario I could not find any article or blog on this.我正在 node js 中学习新概念,即事件,但我找不到应该在哪里使用它,我想要任何真实的场景,我找不到任何关于此的文章或博客。

var events = require('events');
var eventEmitter = new events.EventEmitter();

//Create an event handler:
var myEventHandler = function () {
  console.log('I hear a scream!');
}

//Assign the event handler to an event:
eventEmitter.on('scream', myEventHandler);
eventEmitter.on('test', function(){
    console.log("Testing event");
});

//Fire the 'scream' event:
eventEmitter.emit('scream');
eventEmitter.emit('scream');
eventEmitter.emit('test');

I can achive same thing by simple call function like myEvenHandler() ?我可以通过像myEvenHandler()这样的简单调用函数来达到同样的myEvenHandler()吗?

Yes, in your case you can just call myEventHandler() , but it's a naive example.是的,在您的情况下,您可以只调用myEventHandler() ,但这是一个天真的例子。 Imagine you want to listen different events from an emitter.想象一下,您想从一个发射器监听不同的事件。 For instance, in Mongoose database library:例如,在 Mongoose 数据库库中:

mongoose.connect(databaseUrl); 

mongoose.connection.on('connected', function () {  
    //connected successfully
}); 

mongoose.connection.on('error',function (err) {  
    //connection error
}); 

mongoose.connection.on('disconnected', function () {  
    //disconnected
});

You could pass 3 callbacks to connect() method but by using EventEmitter you have a more readable code (at least, for me) and it allows you to have several listeners throughout your application.您可以将 3 个回调传递给connect()方法,但是通过使用EventEmitter您可以获得更易读的代码(至少对我而言),并且它允许您在整个应用程序中拥有多个侦听器。

Its useful when you have a one to many relationship in your code.当您的代码中有一对多关系时,它很有用。 ie: A single event triggers many things to happen.即:单个事件触发许多事情发生。

The major benefit is decoupling of your code, you can register callbacks on an event emitter without it ever knowing what exactly those callbacks do.主要的好处是你的代码解耦,你可以在事件发射器上注册回调,而它永远不知道这些回调到底做了什么。 One example where I used the pattern was a custom implementation of the Flux pattern.我使用该模式的一个示例是 Flux 模式的自定义实现。 The Dispatcher would get callbacks registered on it, and anytime one of the front end components changed, the Dispatcher would emit an update event. Dispatcher 会在其上注册回调,并且只要前端组件之一发生更改,Dispatcher 就会发出更新事件。 (calling all the registered callbacks) (调用所有注册的回调)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM