Node.js learning and chatting about the Events module
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!
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
onmethods 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
ForRegarding the publish and subscribe model inpublish and subscribe model, you can refer to my previous blog article.
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);
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) }); }
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);
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方法实现 ) } }
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);
on and
off.
// once 方法 EventEmitter.prototype.once = function (eventName, callBack) { const one = () => { callBack(); this.off(eventName, one); } this.on(eventName, one); }
off method before executing the
once method.
once method
(the off method has already been processed)
.
EventEmitter.prototype.once = function (eventName, callBack) { const one = () => { // ... } one.c = callBack; // 自定义一个属性 // ... }
once method.
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!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

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

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!

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 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!

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?

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

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".

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!
