当前位置: 首页 > article >正文

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,您可以添加类型注解。

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!

.


http://www.kler.cn/news/355004.html

相关文章:

  • 云手机:社交平台运营的热门工具
  • 王爽汇编语言第三版实验1
  • 基于springboot的学习平台系统
  • 两种常见的磁盘分区样式及它们的区别总结
  • HttpUtils 详解
  • k8s jenkins 2.421动态创建slave
  • linux 内核如何读取你配置好的.config文件
  • 【CentOS】Shell脚本案例:归档文件
  • C++从入门到起飞之——红黑树 全方位剖析!
  • 【Flutter 面试题】 Flutter如何使用路由、全局错误捕获和自定义组件统一管理错误页面?
  • SpringBoot3响应式编程全套-R2DBC
  • 模板方法设计模式
  • hdfs API操作 hadoop3.3.5
  • java项目技术架构图-样例
  • mysql--表的约束
  • 【Ubuntu】虚拟机共享文件夹启用
  • NFTScan | 10.07~10.13 NFT 市场热点汇总
  • vmware ubuntu根分区扩容
  • 纯前端如何实现批量下载功能呢?
  • ChatGPT免费使用:人工智能在现代社会中的作用