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!

.

相关推荐
炫饭第一名5 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
进击的尘埃7 小时前
Vue3 响应式原理:从 Proxy 到依赖收集,手撸一个迷你 reactivity
javascript
willow7 小时前
JavaScript数据类型整理1
javascript
LeeYaMaster7 小时前
20个例子掌握RxJS——第十一章实现 WebSocket 消息节流
javascript·angular.js
UIUV8 小时前
RAG技术学习笔记(含实操解析)
javascript·langchain·llm
颜酱10 小时前
理解二叉树最近公共祖先(LCA):从基础到变种解析
javascript·后端·算法
FansUnion10 小时前
我如何用 Next.js + Supabase + Cloudflare R2 搭建壁纸销售平台——月成本接近 $0
javascript
左夕11 小时前
分不清apply,bind,call?看这篇文章就够了
前端·javascript
滕青山12 小时前
文本行过滤/筛选 在线工具核心JS实现
前端·javascript·vue.js
时光不负努力12 小时前
编程常用模式集合
前端·javascript·typescript