Previous words
The events module is the core module of node. Almost all commonly used node modules inherit the events module, such as http, fs, etc. This article will introduce the event mechanism in nodeJS in detail
EventEmitter
Most Node.js core APIs adopt the usual asynchronous event-driven architecture, in which certain types of objects (called a trigger) periodically fires a named event to call a function object (listener). For example, a net.Server object will trigger an event every time there is a new connection; an fs.ReadStream will trigger an event when a file is opened; a stream will trigger an event when the data is readable.
【EventEmitter】
The EventEmitter class is defined and open by the events module. All objects that can trigger events are instances of the EventEmitter class
var EventEmitter = require('events');/*{ [Function: EventEmitter] EventEmitter: [Circular], usingDomains: false, defaultMaxListeners: [Getter/Setter], init: [Function], listenerCount: [Function] } */console.log(EventEmitter);
The EventEmitter property of the events module points to the module itself
var events = require('events'); console.log(events.EventEmitter === events);//true
EventEmitter is a constructor that can be used to generate an instance emitter of the event generator
var EventEmitter = require('events');var emitter = new EventEmitter();/*EventEmitter { domain: null, _events: {}, _eventsCount: 0, _maxListeners: undefined } */console.log(emitter);
Method
【emitter.emit(eventName[, ...args])】
eventName <any>...args <any></any></any>
This method is based on the registration order of the listener. , synchronously calls each listener registered to the event named eventName, passing in the provided parameters. If the event has a listener, it returns true, otherwise it returns false
var EventEmitter = require('events');var emitter = new EventEmitter(); emitter.on('test1',function(){}); console.log(emitter.emit('test1'));//trueconsole.log(emitter.emit('test2'));//false
【emitter.on(eventName, listener)】
This method is used to add the listener function to The end of the listener array for the event named eventName
eventName <any> 事件名 listener <function> 回调函数</function></any>
[Note] Does not check whether the listener has been added. Calling multiple times and passing in the same eventName and listener will cause the listener to be added and called multiple times
var EventEmitter = require('events');var emitter = new EventEmitter(); emitter.on('test',function(){ console.log(1); }); emitter.on('test',function(){ console.log(2); }); emitter.emit('test');//1 2
This method returns an EventEmitter reference and can be called in a chain
var EventEmitter = require('events');var emitter = new EventEmitter(); emitter.on('test',function(){ console.log(1); }).on('test',function(){ console.log(2); }); emitter.emit('test');//1 2
【emitter.addListener(eventName, listener)】
Alias of emitter.on(eventName, listener)
var EventEmitter = require('events');var emitter = new EventEmitter(); emitter.addListener('test',function(){ console.log(1); }); emitter.emit('test');//1
【emitter.prependListener ()】
Unlike the on() method, the prependListener() method can be used to add an event listener to the beginning of the listener array
var EventEmitter = require('events');var emitter = new EventEmitter(); emitter.on('test',function(){ console.log(1); }).prependListener('test',function(){ console.log(2); }); emitter.emit('test');//2 1
【emitter.once (eventName, listener)】
This method adds a one-time listener function to the event named eventName. The next time the eventName event is triggered, the listener will be removed and then called
eventName <any> 事件名 listener <function> 回调函数</function></any>
var EventEmitter = require('events');var emitter = new EventEmitter(); emitter.on('test',function(){ console.log(1); }).once('test',function(){ console.log(2); }); emitter.emit('test');//1 2emitter.emit('test');//1
【emitter.prependOnceListener()】
Method is used to add an event listener to the beginning of the listener array. The next time the eventName event is triggered, the listener will be removed and then called
var EventEmitter = require('events');var emitter = new EventEmitter(); emitter.on('test',function(){ console.log(1); }).prependOnceListener('test',function(){ console.log(2); }); emitter.emit('test');//2 1emitter.emit('test');//1
[emitter.removeAllListeners([eventName])]
eventName <any></any>
Remove all or specified eventName listeners, return an EventEmitter reference, which can be called in a chain
[Note] It is a bad practice to remove listeners added elsewhere in the code, especially When the EventEmitter instance is created by other components or modules (such as socket or file stream)
var EventEmitter = require('events');var emitter = new EventEmitter(); emitter.on('test',function(){ console.log(1); }).removeAllListeners('test'); emitter.emit('test');//''
【emitter.removeListener(eventName, listener)】
eventName <any>listener <function></function></any>
Remove the specified listener from the listener array of the event named eventName
var EventEmitter = require('events');var emitter = new EventEmitter();function show(){ console.log(1); } emitter.on('test',show).removeListener('test',show); emitter.emit('test');//''
[Note] removeListener will only remove at most one listener instance from the listener array . If any single listener is added multiple times to the listener array for a specified eventName, removeListener must be called multiple times to remove each instance
var EventEmitter = require('events');var emitter = new EventEmitter();function show(){ console.log(1); } emitter.on('test',show).on('test',show).removeListener('test',show); emitter.emit('test');//'1'
[Note] Once an event is triggered, all listeners bound to it will be triggered in sequence. This means that any call to removeListener() or removeAllListeners() after the event fires but before the last listener has finished executing will not remove them from emit() . Subsequent events will occur as expected. Because listeners are managed using internal arrays, calling this will change the position index of any listeners registered after the listener has been removed. Although this does not affect the order in which the listeners are called, it means that the copy of the listener array returned by the emitter.listeners() method needs to be recreated
var EventEmitter = require('events');var emitter = new EventEmitter();function show1(){ console.log(1); emitter.removeListener('test',show2); }function show2(){ console.log(2); } emitter.on('test',show1).on('test',show2); emitter.emit('test');//1 2emitter.emit('test');//1
Setting
[emitter.eventNames()]
Returns an array listing the events for which the trigger has registered listeners. The value in the array is a string or symbol
var EventEmitter = require('events');var emitter = new EventEmitter(); emitter.addListener('test1',function(){console.log(1);}); emitter.addListener('test2',function(){console.log(2);}); console.log(emitter.eventNames());//[ 'test1', 'test2' ]
eventName <any> 正在被监听的事件名</any>
var EventEmitter = require('events');var emitter = new EventEmitter(); emitter.addListener('test',function(){console.log(1);}); emitter.addListener('test',function(){console.log(1);}); console.log(emitter.listenerCount('test'));//2
eventName <any></any>
var EventEmitter = require('events');var emitter = new EventEmitter(); emitter.addListener('test',function(){console.log(1);}); emitter.addListener('test',function(){console.log(2);}); console.log(emitter.listeners('test'));//[ [Function], [Function] ]emitter.listeners('test')[0]();//1
【emitter.getMaxListeners()】
返回 EventEmitter 当前的最大监听器限制值
var EventEmitter = require('events');var emitter = new EventEmitter(); console.log(emitter.getMaxListeners());//10
【emitter.setMaxListeners(n)】
默认情况下,如果为特定事件添加了超过 10 个监听器,则 EventEmitter 会打印一个警告。 此限制有助于寻找内存泄露。 但是,并不是所有的事件都要被限为 10 个。 emitter.setMaxListeners() 方法允许修改指定的 EventEmitter 实例的限制。 值设为 Infinity(或 0)表明不限制监听器的数量。返回一个 EventEmitter 引用,可以链式调用
var EventEmitter = require('events');var emitter = new EventEmitter(); emitter.on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){});/*Warning: Possible EventEmitter memory leak detected. 11 a listeners added. Use emitter.setMaxListeners() to increase limit */
var EventEmitter = require('events');var emitter = new EventEmitter(); emitter.setMaxListeners(11); emitter.on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){});
【EventEmitter.defaultMaxListeners】
每个事件默认可以注册最多10个监听器。单个EventEmitter实例的限制可以使用emitter.setMaxListeners(n)方法改变。所有EventEmitter实例的默认值可以使用EventEmitter.defaultMaxListeners属性改变
[注意]设置 EventEmitter.defaultMaxListeners 要谨慎,因为会影响所有EventEmitter 实例,包括之前创建的。因而,调用 emitter.setMaxListeners(n) 优先于 EventEmitter.defaultMaxListeners
var EventEmitter = require('events');var emitter = new EventEmitter(); EventEmitter.defaultMaxListeners = 11; emitter.on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){}).on('a',function(){});
事件
【'newListener' 事件】
eventName <any> 要监听的事件的名称 listener <function> 事件的句柄函数</function></any>
EventEmitter 实例会在一个监听器被添加到其内部监听器数组之前触发自身的 'newListener' 事件
注册了 'newListener' 事件的监听器会传入事件名与被添加的监听器的引用。事实上,在添加监听器之前触发事件有一个微妙但重要的副作用: 'newListener' 回调中任何额外的被注册到相同名称的监听器会在监听器被添加之前被插入
var EventEmitter = require('events');var emitter = new EventEmitter(); emitter.on('newListener',function(){ console.log(2); }) emitter.on('test',function(){ console.log(1); }) emitter.emit('test');//2 1
var EventEmitter = require('events');var emitter = new EventEmitter(); emitter.on('test',function(){ console.log(1); }) emitter.on('newListener',function(){ console.log(2); }) emitter.emit('test');//1
【'removeListener' 事件】
eventName <any> 事件名 listener <function> 事件句柄函数</function></any>
'removeListener' 事件在 listener 被移除后触发
var EventEmitter = require('events');var emitter = new EventEmitter();function show(){ console.log(1); } emitter.on('removeListener',function(){ console.log(2);//2}) emitter.on('test',show).removeListener('test',show);
var EventEmitter = require('events');var emitter = new EventEmitter();function show(){ console.log(1); } emitter.on('test',show).removeListener('test',show); emitter.on('removeListener',function(){ console.log(2);//''})
var EventEmitter = require('events');var emitter = new EventEmitter();function show(){ console.log(1); } emitter.removeListener('test',show); emitter.on('removeListener',function(){ console.log(2);//''})
The above is the detailed content of Example tutorial of events in nodeJS events. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools