手写node事件发布订阅

简介

node中的事件是必然要用到的,这也就让了解node事件机制变得很有必要,了解下原来总是好的。简单贴下代码,方便查阅学习。

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
function EventEmitter(){
this._events = {}
}
// 订阅
EventEmitter.prototype.on = function (eventName,callback) {
if(!this._events){
this._events = Object.create(null);
}
// 当前绑定的事件 不是newListener事件就触发newListener事件
if(eventName !== 'newListener'){
this.emit('newListener',eventName)
}
if(this._events[eventName]){
this._events[eventName].push(callback)
}else{
this._events[eventName] = [callback]
}
}
// 发布
EventEmitter.prototype.emit = function (eventName,...args) {
if(!this._events) return
if(this._events[eventName]){
this._events[eventName].forEach(fn=>fn(...args))
}
}
// 绑定一次
EventEmitter.prototype.once = function (eventName,callback) {
const once = (...args) =>{
callback(...args);
// 当绑定后将自己移除掉
this.off(eventName,once);
}
once.l = callback; // 用来标识这个once是谁的
this.on(eventName,once)
}
// 删除
EventEmitter.prototype.off = function (eventName,callback) {
if(!this._events) return
this._events[eventName] = this._events[eventName].filter(fn=>((fn !== callback) && (fn.l!=callback)))
}
module.exports = EventEmitter
-------------本文结束感谢您的阅读-------------

本文标题:手写node事件发布订阅

文章作者:Water

发布时间:2020年09月27日 - 15:09

最后更新:2023年08月01日 - 06:08

原始链接:https://water.buging.cn/2020/09/27/手写node事件发布订阅/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

坚持原创技术分享,您的支持将鼓励我继续创作!