Table of Contents
Events module
off
once
Home Web Front-end JS Tutorial Node.js learning and chatting about the Events module

Node.js learning and chatting about the Events module

Dec 24, 2021 pm 06:18 PM
node.js

This article will take you to understand the Events module in Node.js and introduce the publish and subscribe model in Events. I hope it will be helpful to everyone!

Node.js learning and chatting about the Events module

Events module

Reference official website: events event trigger | Node.js

http ://nodejs.cn/api/events.html

Events module is the most important module of Node. It provides an attribute EventEmitter,# The core of ##EventEmitter is event emission and event listener. Most of the modules in

Node inherit from the Events module.

  • Events module is Node’s implementation of publish/subscribe mode (publish/subscribe). One object passes messages to another object through this module.
  • This module provides a constructor through the
  • EventEmitter attribute. Instances of this constructor have on methods that can be used to listen to specified events and trigger callback functions.
  • Any object can publish specified events, which are monitored by the on method of the
  • EventEmitter instance.

Publish and subscribe model

For

publish and subscribe model, you can refer to my previous blog article.

Regarding the publish and subscribe model in

Events, we must first understand several of its common methods.

  • Subscription method: on method is used to subscribe to events. Subscription maps methods into a one-to-many relationship.
  • Publishing method: emit Used to execute subscribed events.
  • Unsubscribe: The off method can remove the corresponding event listener.
  • Subscribe once: once The bound event automatically deletes the subscribed event after execution.

on and emit

on The first parameter of the method is used to set the class name, and the second parameter is also a Function, which can receive parameters passed in when publishing.

emit The first parameter of the method is the class name, and the subsequent parameters are the parameters passed into the on method function.

on and emit For specific applications, please refer to the simple Demo below.

const EventEmitter = require('events');
// 自定义一个 构造函数
function Cat() {}
// 原型继承 需要通过实例来调用继承方法
Object.setPrototypeOf(Cat.prototype, EventEmitter.prototype);
let cat = new Cat();
const sleep = (a, b) => {
    console.log(a, '睡');
};
const eat = (a, b) => {
    console.log(b, '吃');
};
cat.on('猫咪', sleep)
cat.on('猫咪', eat)
setTimeout(() => {
  	// 小胡子 吃
  	// 小胖仙 睡
    cat.emit('猫咪', '小胖仙', '小胡子')
}, 1000);
Copy after login

Now we can implement a set of

on and emit methods.

function EventEmitter() {
    this._event = {}
}
// on 方法
EventEmitter.prototype.on = function (eventName, callBack) {
    if (!this._event) {
        this._event = {}
    }
    if (this._event[eventName]) {
        this._event[eventName].push(callBack) // 相当于 {eventName:[fn1,fn2]}
    } else {
        this._event[eventName] = [callBack]; // 相当于 {eventName:[fn1]}
    }

}
// emit 方法
EventEmitter.prototype.emit = function (eventName, ...args) {
    this._event[eventName].forEach(fn => {
        fn(...args)
    });
}
Copy after login

off

off The first parameter of the method is used to set the class name, and the second parameter passed in needs to be removed function callback.

// ...
setTimeout(() => {
  	// 小胡子 吃
  	// 小胖仙 睡
    cat.emit('猫咪', '小胖仙', '小胡子')
  	cat.off('猫咪', sleep);
  	// 小胡子 吃
    cat.emit('猫咪', '小胖仙', '小胡子')
}, 1000);
Copy after login

In this way, we can roughly judge and remove the function that is the same as the function we passed in. We quickly thought of the

filter method.

// off 方法
EventEmitter.prototype.off = function (eventName, callBack) {
    if (this._event && this._event[eventName]) {
        this._event[eventName] = this._event[eventName].filter(
          fn => fn !== callBack && fn.c !== callBack // fn.c参考下面的once方法实现
        )
    }
}
Copy after login

once

once The first parameter of the method is used to set the class name. The second parameter is passed in and only needs to be executed once. function callback.

// ...
const demolition =() => {
    console.log('拆家');
}
cat.once('猫咪', demolition)
setTimeout(() => {
  	// ...... 拆家
    cat.emit('猫咪', '小胖仙', '小胡子')
}, 1000);
Copy after login

So we can implement this method based on the previously implemented

on and off.

// once 方法
EventEmitter.prototype.once = function (eventName, callBack) {
    const one = () => {
        callBack();
        this.off(eventName, one);
    }
    this.on(eventName, one);
}
Copy after login

It seems that there is nothing wrong with this method, and it is all executed correctly.

But in a special case, an error still occurred.

That situation is if we have removed it through the

off method before executing the once method.

The method we implemented cannot meet this requirement, so we still need to make some modifications to the

once method (the off method has already been processed) .

Add a custom attribute to "cache" the function.

EventEmitter.prototype.once = function (eventName, callBack) {
    const one = () => {
        // ...
    }
    one.c = callBack; // 自定义一个属性
    // ...
}
Copy after login

In this way we have implemented the

once method.

For more node-related knowledge, please visit:

nodejs tutorial! !

The above is the detailed content of Node.js learning and chatting about the Events module. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

Node.js 19 is officially released, let's talk about its 6 major features! Node.js 19 is officially released, let's talk about its 6 major features! Nov 16, 2022 pm 08:34 PM

Node 19 has been officially released. This article will give you a detailed explanation of the 6 major features of Node.js 19. I hope it will be helpful to you!

Let's talk about how to choose the best Node.js Docker image? Let's talk about how to choose the best Node.js Docker image? Dec 13, 2022 pm 08:00 PM

Choosing a Docker image for Node may seem like a trivial matter, but the size and potential vulnerabilities of the image can have a significant impact on your CI/CD process and security. So how do we choose the best Node.js Docker image?

Let's talk about the GC (garbage collection) mechanism in Node.js Let's talk about the GC (garbage collection) mechanism in Node.js Nov 29, 2022 pm 08:44 PM

How does Node.js do GC (garbage collection)? The following article will take you through it.

What should I do if node cannot use npm command? What should I do if node cannot use npm command? Feb 08, 2023 am 10:09 AM

The reason why node cannot use the npm command is because the environment variables are not configured correctly. The solution is: 1. Open "System Properties"; 2. Find "Environment Variables" -> "System Variables", and then edit the environment variables; 3. Find the location of nodejs folder; 4. Click "OK".

Let's talk about the event loop in Node Let's talk about the event loop in Node Apr 11, 2023 pm 07:08 PM

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

See all articles