发布订阅模式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 @ 2022-06-23 15:49  清风~~徐来  阅读(62)  评论(0编辑  收藏  举报