Home >Web Front-end >JS Tutorial >Node.js learning and chatting about the Events module

Node.js learning and chatting about the Events module

青灯夜游
青灯夜游forward
2021-12-24 18:18:274318browse

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);

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)
    });
}

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);

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方法实现
        )
    }
}

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);

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);
}

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; // 自定义一个属性
    // ...
}

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:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete