JS_用发布订阅模式解耦

js写法

js 复制代码
class EventEmitter {
    constructor() {
        this.listeners = {
            'API:UN_AUTH': new Set(),
            'API:INVALID': new Set()
        }
    }

    on(event, listener) {
        if (this.listeners[event]) {
            this.listeners[event].add(listener)
        } else {
            console.warn(`Event ${event} is not supported.`)
        }
    }

    emit(event, ...args) {
        if (this.listeners[event]) {
            this.listeners[event].forEach(listener => listener(...args))
        }
    }

    off(event, listener) {
        if (this.listeners[event]) {
            this.listeners[event].delete(listener)
        }
    }
}

// 示例用法
const emitter = new EventEmitter()
const onAuth = () => console.log('Unauthorized access!')
emitter.on('API:UN_AUTH', onAuth)
emitter.emit('API:UN_AUTH')  // 输出: Unauthorized access!

ts写法

字段声明:确保使用 private 或 public 关键字正确声明字段。

方法:添加了 on、emit 和 off 方法来管理事件。

类型注解:如果您使用 TypeScript,您可以添加类型注解。

ts 复制代码
class EventEmitter {
    // 使用 public 或 private 声明字段
    private listeners: { [event: string]: Set<Function> } = {
        'API:UN_AUTH': new Set(),
        'API:INVALID': new Set()
    }

    // 添加事件监听器
    public on(event: string, listener: Function) {
        if (this.listeners[event]) {
            this.listeners[event].add(listener)
        } else {
            console.warn(`Event ${event} is not supported.`)
        }
    }

    // 触发事件
    public emit(event: string, ...args: any[]) {
        if (this.listeners[event]) {
            this.listeners[event].forEach(listener => listener(...args))
        }
    }

    // 移除事件监听器
    public off(event: string, listener: Function) {
        if (this.listeners[event]) {
            this.listeners[event].delete(listener)
        }
    }
}

// 示例用法
const emitter = new EventEmitter()
const onAuth = () => console.log('Unauthorized access!')
emitter.on('API:UN_AUTH', onAuth)
emitter.emit('API:UN_AUTH')  // 输出: Unauthorized access!

.

相关推荐
西阳未落8 分钟前
C语言中的内存函数(memcpy, memmove, memcmp, memset)
c语言·开发语言
axban2 小时前
QT M/V架构开发实战:QFileSystemModel介绍
开发语言·qt·架构
钢门狂鸭4 小时前
关于rust的crates.io
开发语言·后端·rust
Lionel_SSL5 小时前
《深入理解Java虚拟机》第三章读书笔记:垃圾回收机制与内存管理
java·开发语言·jvm
技术猿188702783515 小时前
PHP 与 WebAssembly 的 “天然隔阂”
开发语言·php·wasm
薄荷撞~可乐5 小时前
C#Task(Api)应用
开发语言·c#
雾恋7 小时前
最近一年的感悟
前端·javascript·程序员
华仔啊7 小时前
Vue3 的 ref 和 reactive 到底用哪个?90% 的开发者都选错了
javascript·vue.js
another heaven7 小时前
【Qt VS2022调试时无法查看QString等Qt变量信息】解决方法
开发语言·qt
A黄俊辉A7 小时前
axios+ts封装
开发语言·前端·javascript