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!

.

相关推荐
小樱花的樱花6 分钟前
Linux 线程的创建
linux·c语言·开发语言
xiaoshuaishuai826 分钟前
C# AI实现PR处理、单元测试
开发语言·c#·log4j
C++、Java和Python的菜鸟26 分钟前
第7章 Java高级技术
java·开发语言
LONGZHIQIN28 分钟前
C#基础复习笔记
开发语言·笔记·c#
可靠的仙人掌43 分钟前
SAC(Soft Actor-Critic)算法底座
开发语言·算法·php
学逆向的1 小时前
汇编——数据存储模式
开发语言·汇编·网络安全
geovindu1 小时前
CSharp: Prototype Pattern
开发语言·后端·设计模式·.net·原型模式·创建型模式
天天进步20152 小时前
Python全栈项目--校园食堂点餐与推荐系统
开发语言·python
aaPIXa6222 小时前
C++模板元编程:编译期计算Fibonacci数列
java·开发语言·c++
eybk2 小时前
写一个可以编制pdf文件的python程序
开发语言·python·pdf