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!

.

相关推荐
2351626 分钟前
【并发编程】详解volatile
java·开发语言·jvm·分布式·后端·并发编程·原理
Algebraaaaa1 小时前
Qt中的字符串宏 | 编译期检查和运行期检查 | Qt信号与槽connect写法
开发语言·c++·qt
Red Car1 小时前
javascript 性能优化实例一则
开发语言·javascript·ecmascript
友友马1 小时前
『 QT 』Hello World控件实现指南
开发语言·qt
艾小码1 小时前
从Hello World到变量数据类型:JavaScript新手避坑指南
前端·javascript
一只学java的小汉堡1 小时前
Java 面试高频题:HashMap 与 ConcurrentHashMap 深度解析(含 JDK1.8 优化与线程安全原理)
java·开发语言·面试
huohaiyu2 小时前
Hashtable,HashMap,ConcurrentHashMap之间的区别
java·开发语言·多线程·哈希
千叶寻-2 小时前
正则表达式
前端·javascript·后端·架构·正则表达式·node.js
Predestination王瀞潞6 小时前
IO操作(Num22)
开发语言·c++
宋恩淇要努力8 小时前
C++继承
开发语言·c++