Nodejs has an important event module: EventEmitter.
It is widely used in Nodejs built-in and third-party modules, and many Nodejs project architectures are implemented with it.
Visible, EventEmitter is very important for learning NodeJS.
Below, we use routines to understand and master EventEmitter.
var EventEmitter = require(&39;events&39;).EventEmitter;
var event = new EventEmitter();
//Trigger some_event
setTimeout(function() {
event.emit( &39;some_event&39;);
}, 1000);
//Responding to some_event event
event.on(&39;some_event&39;, function() {
console.log(&39;some_event event trigger&39; );
});
This code first initializes an instance of EventEmitter, and then one second later, triggers an event, the event name is some_event, and in this event Output information in the response function. The execution effect of
is shown in the figure:
Each event of EventEmitter consists of an event name and several parameters. The event name is a string, which usually expresses a certain Semantics. For each event, EventEmitter supports several event listeners.
When an event is triggered, the event listeners registered to this event are called in turn, and the event parameters are passed as callback function parameters, as shown in the following example:
Execution effect:
In the above example, the emitter registers two event listeners for the event someEvent, and then triggers the someEvent event.
In the running result, you can see that the two event listener callback functions are called successively. This is the simplest usage of EventEmitter.
If you have been in contact with NodeJS before, will you feel familiar? For example, in Express, the common connection method. It is constructed in this way.
More articles in this series:
Node.js actual combat 7: Do you know buffer ?
Node.js combat 6: Timer, use timer to delay execution