Home>Article>Web Front-end> Detailed explanation of events in Node.js
Related recommendations: "nodejs Tutorial"
The front-end is certainly no stranger to events, binding the scroll event for the window
window.addEventListener('scroll', ev => { console.log(ev); });
Node.js Most asynchronous operations are event-driven. All objects that can trigger events inherit theEventEmitter
class
Node.js event listening is very similar to jQuery APIemitter.on(eventName, listener)
const ee = new EventEmitter(); ee.on('foo', () => console.log('a'));
emitter.prependListener(eventName, listener)
You can add the listener to the head of the listener array through prependListener
const ee = new EventEmitter(); ee.prependListener('foo', () => console.log('a'));
If you want the listener to be triggered once and then no longer trigger, you can use once to bind the event
const ee = new EventEmitter(); ee.once('foo', () => console.log('a'));
emitter.emit(eventName[, ... args])
Most of the developer's event-related work in the browser environment is to subscribe to events, that is, to bind the event processing function listener. In Node.js event programming, it is often necessary to create event objects. The actual trigger event. Use the emit method tosynchronouslycall each listener registered to the event named eventName in the order of listener registration, and pass in the provided parameters
const EventEmitter = require('events'); const myEmitter = new EventEmitter(); // 第一个监听器。 myEmitter.on('event', function firstListener() { console.log('第一个监听器'); }); // 第二个监听器。 myEmitter.on('event', function secondListener(arg1, arg2) { console.log(`第二个监听器中的事件有参数 ${arg1}、${arg2}`); }); // 第三个监听器 myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(`第三个监听器中的事件有参数 ${parameters}`); }); console.log(myEmitter.listeners('event')); myEmitter.emit('event', 1, 2, 3, 4, 5); // Prints: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // 第一个监听器 // 第二个监听器中的事件有参数 1、2 // 第三个监听器中的事件有参数 1, 2, 3, 4, 5
eventEmitter.emit()
The method can pass any number of parameters to the listener.this
The keyword will be pointed to the EventEmitter instance bound to the listener
const myEmitter = new MyEmitter(); myEmitter.on('event', function(a, b) { console.log(a, b, this, this === myEmitter); // 打印: // a b MyEmitter { // domain: null, // _events: { event: [Function] }, // _eventsCount: 1, // _maxListeners: undefined } true }); myEmitter.emit('event', 'a', 'b');
You can also use ES6 arrow functions as listeners. Butthis
keyword will not point to the EventEmitter instance:
const myEmitter = new MyEmitter(); myEmitter.on('event', (a, b) => { console.log(a, b, this); // 打印: a b {} }); myEmitter.emit('event', 'a', 'b');
EventEmitter
Call all listeners synchronously in the order of registration, so that To ensure the correct ordering of events, the listener can use thesetImmediate()
andprocess.nextTick()
methods to switch to asynchronous operation mode
const myEmitter = new MyEmitter(); myEmitter.on('event', (a, b) => { setImmediate(() => { console.log('异步地发生'); }); }); myEmitter.emit('event', 'a', 'b');
Node.js provides several methods for uninstalling event bindings
The off method is an alias of the removeListener method and is used to clean up event bindingsemitter.removeListener(eventName, listener)
const callback = (stream) => { console.log('已连接'); }; server.on('connection', callback); // ... server.removeListener('connection', callback);
removeListener() will only remove at most one listener from the listener array. If a listener is added multiple times to the listener array for a specified eventName, removeListener() must be called multiple times to remove all instances
emitter. removeAllListeners([eventName])
Remove the listener of the specified eventName event. If eventName is not specified, remove all listeners of the event object. You can get the eventName array on the event object throughemitter.eventNames()
const EventEmitter = require('events'); const myEE = new EventEmitter(); myEE.on('foo', () => {}); myEE.on('bar', () => {}); myEE.eventNames().forEach(eventName => myEE.removeAllListeners);
For more programming-related knowledge, please visit:Programming Video! !
The above is the detailed content of Detailed explanation of events in Node.js. For more information, please follow other related articles on the PHP Chinese website!