This article mainly introduces the event mechanism of node. This article implements a simple event mechanism with publish/subscribe mode to clarify the implementation ideas of the EventEmitter class. If you are interested, you can learn more. I hope it can help. Everyone.
Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.
In the official documentation of nodejs, it is clearly written One of the features of node is event-driven, which shows that it is very important. Looking at the source code, we can see that its event mechanism is the EventEmitter class written in js, which is very elegantly written and applies the publish/subscribe model.
By implementing a simple event mechanism with publish/subscribe mode, we can clarify the implementation ideas of the EventEmitter class
Publish/Subscribe (publish/subscribe mode)
ANAlogy
What we are talking about is a pattern. The word pattern sounds very abstract. Let’s give a chestnut first. Suppose there is a newspaper organization that provides morning, afternoon, and evening newspapers. If you want to read a certain newspaper, you need to subscribe to the newspaper organization. When the corresponding newspaper is released, the newspaper organization will notify you to pick up the newspaper.
In this process, the newspaper organization has implemented two functions. One is to accept customer subscriptions; the other is to publish different types of newspapers. When a newspaper is published, customers who subscribe to that type of newspaper will receive notifications.
This newspaper organization is the event mechanism we want to implement.
Purpose
It can be seen from the above example: 1. Publish the newspaper; 2. Give the newspaper to the customer; this Due to the existence of the newspaper organization, the continuous process can be subscribed first and then published. When it is published, it will be automatically sent to the customer, realizing the separation of action time. This is also the advantage of the publish/subscribe system.
Implementation ideas
We have 3 types of newspapers, corresponding to 3 events, and customers must be notified when each event occurs. The corresponding data format can be as follows:
var Event = { morning: event1, noon: event2, night: event3 }
Since each newspaper may be subscribed by more than one person, the format can be optimized like this:
var Event = { morning: [e11, e12,...], noon: [e21, e22], night: event3 }
When a user subscribes, we add its event to the corresponding array; when the event is published, the corresponding event is executed. To put it bluntly, store it first and then use it.
The specific code is as follows:
1.on means subscribing, adding the event to the corresponding array
2.emit means publishing, adding the data in the corresponding array Take it out and execute
3.off means deleting useless events
var Event = { on: function(key, listener) { if (!this.__events) { this.__events = {} } if (!this.__events[key]) { this.__events[key] = []; } if (_indexOf(this.__events[key], listener) == -1 && typeof listener === 'function') { this.__events[key].push(listener) } }, emit: function(key) { if (!this.__events || !this.__events[key]) return //取得每次订阅不同的参数 var arg = Array.prototype.slice.call(arguments, 1) || []; var listeners = this.__events[key]; var len = listeners.length; for (var i=0; i<len; i++) { listeners[i].apply(this, arg) } return this }, off: function(key, listener) { if (!key && !listener) { this.__events = {} } if (key && !listener) { delete this.__events[key] } if (key && listener) { var listeners = this.__events[key]; var index = _indexOf(listeners, listener); (index > -1) && listeners.splice(index, 1); } return this } } var _indexOf = function(array,key){ if (array === null) return -1 var i = 0, length = array.length for (; i < length; i++) if (array[i] === key) return i return -1 } //调用 Event.on('console1', function(num) { console.log(num); // 1 }); Event.emit('console1', 1)
node’s EventEmitter
node’s EventEmitter basic logic Basically the same as the example provided above, just more complicated.
1. Subscribe to events on
function _addListener(target, type, listener, prepend) { var m; var events; var existing; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = target._events; ... if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; } else { // If we've already got an array, just append. if (prepend) { existing.unshift(listener); } else { existing.push(listener); } } return target; } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener;
2. Publish events
EventEmitter.prototype.emit = function emit(type) { ... handler = events[type]; switch (len) { // fast cases case 1: emitNone(handler, isFn, this); break; case 2: emitOne(handler, isFn, this, arguments[1]); break; case 3: emitTwo(handler, isFn, this, arguments[1], arguments[2]); break; case 4: emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); break; // slower default: args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; emitMany(handler, isFn, this, args); } }
At this point, I believe everyone already understands the implementation idea of EventEmitter.
Related recommendations:
Implementation of PHP event mechanism
Event mechanism and blocking in jq and js
The above is the detailed content of Explanation of node event mechanism. For more information, please follow other related articles on the PHP Chinese website!

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

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.


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

Notepad++7.3.1
Easy-to-use and free code editor

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.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
