发布订阅模式ts

// 订阅发布模式
type BusClass = {
    emit: (name: string) => void;
    on: (name: string, callback: Function) => void;
    off: (name: string) => void;
    once: (name: string, callback: Function) => void;
};

type PramsKey = string | number | symbol;

type List = {
    [key: PramsKey]: Array<Function>;
};

class Bus implements BusClass {
    list: List;
    constructor() {
        this.list = {};
    }
    // 订阅
    emit(name: string, ...args: Array<any>) {
        if (name in this.list) {
            let eventName: Array<Function> = this.list[name];
            eventName.forEach((fn) => {
                fn.apply(this, args);
            });
        } else {
            console.error(`不存在${name}`)
        }

    }
    // 发布
    on(name: string, callback: Function) {
        let fn: Array<Function> = this.list[name] || [];
        fn.push(callback);
        this.list[name] = fn;
    }
    // 取消订阅
    off(name: string) {
        if (name in this.list) {
            delete this.list[name];
        } else {
            throw `${name} is undefined`;
        }
    }
    // 只调用一次
    once(name: string, callback: Function) {
        let temporaryFn = (...args: Array<any>) => {
            callback.apply(this, args)
            this.off(name)
        }
        this.on(name, temporaryFn)
    }
}

let bus = new Bus();

bus.on('get1', (...args: Array<any>): void => {
    console.log(args, "get11111111111111111111111111111")
})

bus.on('post', (...args: Array<any>): void => {
    console.log(args, "post")
})

bus.emit('get1', 1, 2, 3, 4, 5, 6, 7, 8, 9, [1, 2, 3, 4, 5])
bus.emit('post', 1, [1, 2, 3, 4, 5], { a: 1, b: [10] })
bus.off('post')
bus.off('post22222')
bus.emit('post', 1, 22222, { c: 1, b: [10] })



posted @   清风~~徐来  阅读(65)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示