简体   繁体   中英

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.

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() ?

Yes, in your case you can just call myEventHandler() , but it's a naive example. Imagine you want to listen different events from an emitter. For instance, in Mongoose database library:

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.

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. The Dispatcher would get callbacks registered on it, and anytime one of the front end components changed, the Dispatcher would emit an update event. (calling all the registered callbacks)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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