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()
?
2 Answers
Reset to default 5Yes, 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
版权声明:本文标题:javascript - When to use eventEmitter in Node js? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744201037a2594961.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论