Node.js learning and chatting about the Events module

青灯夜游
Release: 2021-12-24 18:18:27
forward
4151 people have browsed it

This article will take you to understand the Events module inNode.jsand 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

Eventsmodule is the most important module of Node. It provides an attributeEventEmitter,# The core of ##EventEmitteris event emission and event listener. Most of the modules in

Nodeinherit from theEventsmodule.

  • Eventsmodule is Node’s implementation ofpublish/subscribe mode(publish/subscribe). One object passes messages to another object through this module.
  • This module provides a constructor through the
  • EventEmitterattribute. Instances of this constructor haveonmethods 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
  • EventEmitterinstance.

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:onmethod is used to subscribe to events. Subscription maps methods into a one-to-many relationship.
  • Publishing method:emitUsed to execute subscribed events.
  • Unsubscribe: Theoffmethod can remove the corresponding event listener.
  • Subscribe once:onceThe bound event automatically deletes the subscribed event after execution.

on and emit

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

emitThe first parameter of the method is the class name, and the subsequent parameters are the parameters passed into theonmethod function.

onandemitFor 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

onandemitmethods.

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

offThe 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

filtermethod.

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

onceThe 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

onandoff.

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

offmethod before executing theoncemethod.

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

oncemethod(theoffmethod 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

oncemethod.

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!

Related labels:
source:juejin.cn
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!