Event-driven events
Events is the most important module in node. js because the framework of node. JS itself is an event, and events provides a unique interface.
Event Launcher events. Eventemitter
Events. The core of Eventemitter is the encapsulation of event launch and event listener functionality. Each event of a eventemitter consists of an event name and several parameters, which is a string that usually expresses a certain semantics.
For each event, events. Eventemitter supports a number of event listeners. When an event is emitted, the event listener registered to the event is called sequentially, and the event arguments are passed as a callback function parameter.
Eventemitter.on (event, listener) registers a listener for the specified event, accepts a string event, and listener a callback function.
Eventemitter.emit (event, [Arg1],[arg2], [Arg3]..) Launch event events, passing the burst sense optional parameter to the event listener's parameter table.
Eventemitter.once (event, listener) registers a single listener for the specified event, that is, the listener is fired at most once, and the listener is dismissed as soon as it is triggered.
Eventemitter.removelistener (Event,listener) removes a listener for the specified event, listener must be a listener that the event has already registered.
Eventemitter.removealllistener ([Event]) removes the listener for all events and, if specified, removes all listeners for the specified event.
will return emitter to ensure chain operation.
Error Event
Eventemitter defines a special event error that contains the semantics of "error", and Eventemitter specifies that if there is no response listener, node. JS will take it as an exception, exit the program and print the call stack.
It is common to set the listener for the object that emits the error event, avoiding the entire program crashing after encountering an error.
Inherit Eventemitter
Most of the time we don't use eventemitter directly, but we inherit it from the object. Including Fs,net,http, as long as the core module that supports incident response is Eventemitter subclass.
The reason for this: one: An object that has an entity function implements the semantics of the event, and the listener and the launch should be the method of an object.
Two: JavaScript object mechanism is based on prototype, support partial multiple inheritance, inheritance Eventemitter will not disrupt the original inheritance relationship of the object.
node. JS Learning Note 6