The front end is no stranger to events, binding scroll events to Windows

window.addEventListener('scroll'.ev= > {
	console.log(ev);
});
Copy the code

Most of node.js’s asynchronous operations are event-driven, and all objects that can trigger events inherit the EventEmitter class

Event listeners

on

Node.js event listener usage is very similar to jQuery API Emitters. On (eventName, Listener)

const ee = new EventEmitter();
ee.on('foo'.() = > console.log('a'));
Copy the code
  1. EventEmitter instances maintain an array of Listeners, which are added to the end of the array by default
  2. Each time a listener is added, it does not check whether the listener has been added. Multiple calls to ON pass in the same eventName and listener, causing the listener to be added multiple times

prependListener

Emitter. PrependListener (eventName, listener) prependListener allows you to add listeners to the listener array header

const ee = new EventEmitter();
ee.prependListener('foo'.() = > console.log('a'));
Copy the code

once

If you want the listener to be fired once and not fired again, you can use once to bind the event

const ee = new EventEmitter();
ee.once('foo'.() = > console.log('a'));
Copy the code

Events trigger

Emitter. Emit (eventName[,…args]) In the browser environment, most of the work related to developing events is to subscribe to events, that is, bind event handler function listener. In Node.js event programming, it is often necessary to create event objects and trigger events reasonably. Use the emit method to invoke each listener registered to an event named eventName synchronously in the order of listener registration, passing in the supplied parameters

const EventEmitter = require('events');
const myEmitter = new EventEmitter();

// The first listener.
myEmitter.on('event'.function firstListener() {
  console.log('First listener');
});
// The second listener.
myEmitter.on('event'.function secondListener(arg1, arg2) {
  console.log('The event in the second listener has parameters${arg1},${arg2}`);
});
// The third listener
myEmitter.on('event'.function thirdListener(. args) {
  const parameters = args.join(', ');
  console.log('The event in the third listener has parameters${parameters}`);
});

console.log(myEmitter.listeners('event'));

myEmitter.emit('event'.1.2.3.4.5);

// Prints:
/ / /
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// The first listener
// The event in the second listener takes arguments 1 and 2
// The event in the third listener has parameters 1, 2, 3, 4, 5
Copy the code

This points to the

The eventEmitter. Emit () method can pass an arbitrary number of arguments to the Listener. This keyword is referred to the eventEmitter instance that the Listener is bound to

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

You can also use ES6’s arrow functions as listeners. But this keyword does not refer 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

The asynchronous call

EventEmitter calls all Listeners synchronously in a registered order to ensure that events are sorted correctly. Listeners can use setImmediate() and process.nexttick () to switch to an asynchronous mode of operation

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

Event uninstall

Node.js provides several ways to unload event bindings

off/removeListener

The off method is an alias for the removeListener method, used to clean up event bindings emitters. RemoveListener (eventName, listener)

const callback = (stream) = > {
  console.log('Connected');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
Copy the code

RemoveListener () removes at most one listener from the listener array. If listeners are added more than once to the listener array specified for eventName, removeListener() must be called more than once to remove all instances

removeAllListeners

Emitter. RemoveAllListeners ([eventName]) to remove the specified eventName event listener, if you don’t specify eventName, events will remove all the listener object. You can get an array of eventNames on an event object from Emitters. EventNames ()

const EventEmitter = require('events');
const myEE = new EventEmitter();
myEE.on('foo'.() = > {});
myEE.on('bar'.() = > {});

myEE.eventNames().forEach(eventName= > myEE.removeAllListeners);
Copy the code

The minimalist Node. Js introductory tutorial: www.yuque.com/sunluyong/n…

In this paper, a better reading experience: www.yuque.com/sunluyong/n…