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!

.

相关推荐
方也_arkling5 小时前
【Java-Day08】static / final / 枚举
java·开发语言
风吹夏回6 小时前
Python 全局异常处理:从“满屏 try-except”到优雅兜底
开发语言·python
Chengbei116 小时前
一站式源码安全检测工具、云安全 / APP / 小程序源码敏感信息递归多层目录扫描AK、JWT、手机号、身份证等敏感信息
java·开发语言·安全·web安全·网络安全·系统安全·安全架构
llz_1126 小时前
web-第一次课后作业
java·开发语言·idea
小熊Coding6 小时前
Python爬取当当网二手图书项目实战!
开发语言·爬虫·python·beautifulsoup·requests·二手图书
秋96 小时前
Java项目运行5天左右自动宕机:系统性定位与解决方案
java·开发语言·python
xiaoshuaishuai86 小时前
C# 内存管理与资源泄漏
开发语言·c#
lsx2024067 小时前
SVN 检出操作
开发语言
basketball6167 小时前
C++ NULL 和 nullptr 区别 以及 nullptr 的核心实现
java·开发语言·c++
zhangyao9403308 小时前
开发pc端时,表格的高度怎么设置才能铺满页面
前端·javascript·elementui