Home Web Front-end JS Tutorial Explanation of node event mechanism

Explanation of node event mechanism

Jan 26, 2018 pm 01:31 PM
node event

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
}
Copy after login

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
}
Copy after login

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(&#39;console1&#39;, function(num) {
 console.log(num); // 1
});

Event.emit(&#39;console1&#39;, 1)
Copy after login

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 !== &#39;function&#39;)
  throw new TypeError(&#39;"listener" argument must be a function&#39;);

 events = target._events;
 ...
 if (typeof existing === &#39;function&#39;) {
   // Adding the second element, need to change to array.
   existing = events[type] =
    prepend ? [listener, existing] : [existing, listener];
  } else {
   // If we&#39;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;
Copy after login

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);
 }
}
Copy after login

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

JavaScript event mechanism

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use express to handle file upload in node project How to use express to handle file upload in node project Mar 28, 2023 pm 07:28 PM

How to handle file upload? The following article will introduce to you how to use express to handle file uploads in the node project. I hope it will be helpful to you!

Event ID 4660: Object deleted [Fix] Event ID 4660: Object deleted [Fix] Jul 03, 2023 am 08:13 AM

Some of our readers encountered event ID4660. They're often not sure what to do, so we explain it in this guide. Event ID 4660 is usually logged when an object is deleted, so we will also explore some practical ways to fix it on your computer. What is event ID4660? Event ID 4660 is related to objects in Active Directory and will be triggered by any of the following factors: Object Deletion – A security event with Event ID 4660 is logged whenever an object is deleted from Active Directory. Manual changes – Event ID 4660 may be generated when a user or administrator manually changes the permissions of an object. This can happen when changing permission settings, modifying access levels, or adding or removing people or groups

An in-depth analysis of Node's process management tool 'pm2” An in-depth analysis of Node's process management tool 'pm2” Apr 03, 2023 pm 06:02 PM

This article will share with you Node's process management tool "pm2", and talk about why pm2 is needed, how to install and use pm2, I hope it will be helpful to everyone!

Get upcoming calendar events on your iPhone lock screen Get upcoming calendar events on your iPhone lock screen Dec 01, 2023 pm 02:21 PM

On iPhones running iOS 16 or later, you can display upcoming calendar events directly on the lock screen. Read on to find out how it's done. Thanks to watch face complications, many Apple Watch users are used to being able to glance at their wrist to see the next upcoming calendar event. With the advent of iOS16 and lock screen widgets, you can view the same calendar event information directly on your iPhone without even unlocking the device. The Calendar Lock Screen widget comes in two flavors, allowing you to track the time of the next upcoming event, or use a larger widget that displays event names and their times. To start adding widgets, unlock your iPhone using Face ID or Touch ID, press and hold

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

Token-based authentication with Angular and Node Token-based authentication with Angular and Node Sep 01, 2023 pm 02:01 PM

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

What is a single sign-on system? How to implement it using nodejs? What is a single sign-on system? How to implement it using nodejs? Feb 24, 2023 pm 07:33 PM

What is a single sign-on system? How to implement it using nodejs? The following article will introduce to you how to use node to implement a single sign-on system. I hope it will be helpful to you!

In JavaScript, what is the purpose of the 'oninput' event? In JavaScript, what is the purpose of the 'oninput' event? Aug 26, 2023 pm 03:17 PM

When a value is added to the input box, the oninput event occurs. You can try running the following code to understand how to implement oninput events in JavaScript - Example<!DOCTYPEhtml><html> <body> <p>Writebelow:</p> <inputtype="text&quot

See all articles