admin管理员组

文章数量:1400292

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

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

Share Improve this question edited Oct 30, 2017 at 8:14 Ashutosh Jha asked Oct 30, 2017 at 8:03 Ashutosh JhaAshutosh Jha 16.4k11 gold badges58 silver badges86 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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. i.e: 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 ponents changed, the Dispatcher would emit an update event. (calling all the registered callbacks)

本文标签: javascriptWhen to use eventEmitter in Node jsStack Overflow