Most of the core API types in Node (called triggers) fire named events to call functions (called listeners).

For example, Net. Server fires an event every time there is a new connection, fs.ReadStream fires an event when a file is opened, and Stream fires an event when the data is readable.

All objects that can fire events are instances of the EventEmitter class. These objects have an eventEmitter. On () function that binds one or more functions to named events.

When an EventEmitter object fires an event, all functions bound to the event are called synchronously. Any values returned by the invoked listener are ignored and discarded.

Example: A simple EventEmitter instance that binds a listener. Eventemitter.on () is used to register listeners, and eventemitter.emit () is used to fire events.

const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
  console.log('Trigger event');
});
myEmitter.emit('event');
Copy the code

The parameters andthisPass to listener

The eventEmitter. Emit () method can pass any number of arguments to listener functions. When a listener function is called, the this keyword is referred to the EventEmitter instance to which the listener is bound.

const myEmitter = new MyEmitter();
myEmitter.on('event'.function(a, b) { console.log(a, b, this, this === myEmitter); [Function]}, // _eventsCount: 1, // _listeners: undefined }true
});
myEmitter.emit('event'.'a'.'b');
Copy the code

Arrow functions can also be used as listeners, but this keyword does not point to EventEmitter instances:

const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => { console.log(a, b, this); // Print: a b {}}); myEmitter.emit('event'.'a'.'b');
Copy the code

Asynchrony and synchronization

EventEmitter synchronously calls all listeners in the order in which they were registered. You must ensure that events are ordered correctly and race conditions are avoided.

SetImmediate () or process.nexttick () can be used to switch to asynchronous mode:

const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
  setImmediate(() => {
    console.log('Proceed asynchronously');
  });
});
myEmitter.emit('event'.'a'.'b');
Copy the code

Only one event is processed

When listeners are registered with eventEmitter. On (), they are called each time a named event is emitted.

const myEmitter = new MyEmitter();
let m = 0;
myEmitter.on('event', () => {
  console.log(++m);
});
myEmitter.emit('event'); // Print: 1 myEmitter. Emit ('event'); // Print: 2Copy the code

Use eventEmitter.once() to register listeners that can be called at most once. When the event is triggered, the listener is deregistered and then invoked.

const myEmitter = new MyEmitter();
let m = 0;
myEmitter.once('event', () => {
  console.log(++m);
});
myEmitter.emit('event'); // Print: 1 myEmitter. Emit ('event'); / / don't triggerCopy the code

Error events

An ‘error’ event should be emitted when an EventEmitter instance goes wrong. These are treated as special cases in Node.

If no listener is registered for the ‘error’ event, when the ‘error’ event is raised, an error is thrown, a stack trace is printed, and the Node.js process exits.

const myEmitter = new MyEmitter();
myEmitter.emit('error', new Error('Error message')); // Throws an error and crashes Node.js.Copy the code

As a best practice, you should always register listeners for ‘error’ events.

const myEmitter = new MyEmitter();
myEmitter.on('error', (err) => {
  console.error('Error message');
});
myEmitter.emit('error', new Error('wrong')); // Print: error messageCopy the code

EventEmitterclass

EventEmitter class is defined by the Events module:

const EventEmitter = require('events');
Copy the code

newListener

  • Event – Indicates the name of the event
  • Listener – Handles an event function

This event is raised when a new listener is added.

const myEmitter = new MyEmitter(); // Process only once to avoid infinite loops. myEmitter.once('newListener', (event, listener) => {
  if (event === 'event') {// Insert a new listener in front. myEmitter.on('event', () => {
      console.log('B'); }); }}); myEmitter.on('event', () => {
  console.log('A');
});
myEmitter.emit('event'); // Print: // B // ACopy the code

removeListener

  • Event – Indicates the name of the event
  • Listener – Handles an event function

Removes a listener from the specified listener array. It is important to note that this operation will change the indexes of the listeners that are behind the deleted listeners.

myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(EventEmitter.listenerCount(myEmitter, 'event'));
// Prints: 2
Copy the code

addListener(event, listener)

Adds a listener to the end of the listener array for the specified event.

on(event, listener)

Registers a listener for the specified event that accepts a string event and a callback function.

server.on('connection'.function (stream) {
  console.log('someone connected! ');
});
Copy the code

emit(event, [arg1], [arg2], […] )

Each listener is executed in listener order, returning true if the event has a registered listener, false otherwise.

once(event, listener)

Registers a single listener for the specified event, that is, the listener is fired at most once, and then the listener is fired immediately.

server.once('connection'.function (stream) {
  console.log('Ah, we have our first user! ');
});
Copy the code

off(event, listener)

An alias for Emitters. RemoveListener ().

removeListener(event, listener)

Removes a listener for the specified event. the listener must be a listener already registered for the event. It takes two arguments, the event name and the callback function name.

let callback = function(stream) {
  console.log('someone connected! ');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
Copy the code

removeAllListeners([event])

Removes all listeners for all events or, if an event is specified, all listeners for the specified event.

setMaxListeners(n)

By default, EventEmitters outputs warnings if you add more than 10 listeners. SetMaxListeners are used to increase the number of default listeners.

Set EventEmitter. DefaultMaxListeners caution, because will affect all EventEmitter instance, including the previously created. . Thus, use priority emitter setMaxListeners (n) rather than EventEmitter. DefaultMaxListeners.

emitter.setMaxListeners(emitter.getMaxListeners() + 1);
Copy the code

defaultMaxListeners

By default, up to 10 listeners can be registered per event. Limits for individual EventEmitter instances can be changed using the emitters. SetMaxListeners (n) method. Can use EventEmitter. DefaultMaxListeners property change the default values for all EventEmitter instance. If this value is not a positive number, TypeError is thrown.

Set EventEmitter. DefaultMaxListeners caution, because will affect all EventEmitter instance, including the previously created. . Thus, use priority emitter setMaxListeners (n) rather than EventEmitter. DefaultMaxListeners.

emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event'* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * });Copy the code

getMaxListeners()

Returns the current of EventEmitter listeners maximum limit on the number of values, the value you can use the emitter. SetMaxListeners (n) sets or default to EventEmitter. DefaultMaxListeners.

listeners(event)

Returns an array of listeners for the specified event. Returns a copy of the listener array for the event named Event.

server.on('connection', (stream) => {
  console.log('Connected');
});
console.log(util.inspect(server.listeners('connection'))); // Print: [[Function]]Copy the code

listenerCount(emitter, event)

Returns the number of listeners for the specified event.

Events. EventEmitter. ListenerCount (emitter, eventName) / / obsolete, do not recommend events. The emitter. ListenerCount (eventName) / / recommendations

eventNames()

Returns an array of event names for registered listeners. The values in the array are strings or symbols.

const EventEmitter = require('events');
const myEE = new EventEmitter();
myEE.on('foo', () = > {}); myEE.on('bar', () = > {}); const sym = Symbol('symbol'); myEE.on(sym, () => {}); console.log(myEE.eventNames()); // Print: ['foo'.'bar', Symbol(symbol) ]
Copy the code

rawListeners(event)

Returns a copy of the array of listeners for the event event, including encapsulated listeners (such as those created by.once()).

const emitter = new EventEmitter();
emitter.once('log', () => console.log('Record once only')); // Returns an array containing a listener enclosing the 'listener' method. const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0]; // Prints "record once only", but does not unbind the 'once' event.logFnWrapper.listener(); // Print "record once only" and remove the listener.logFnWrapper();

emitter.on('log', () => console.log('Record continuously')); // Returns an array containing only listeners bound to '.on() '. const newListeners = emitter.rawListeners('log'); // Print "continuously record" twice. newListeners[0](); emitter.emit('log');
Copy the code

Come to an end. emmm……….


@ _ @