手写一个Bus总线

type BusClass = {
    emit: (name: string) => void
    on: (name: string, cab: Function) => void
}

type PramsKey = string | number | symbol

type List = {
    [key: PramsKey]: Array
}

class Bus implements BusClass {
    list: List
    constructor() {
        this.list = {}
    }
    emit(name: string, ...args: Array) {
        let eventName: Array = this.list[name];
        eventName.forEach(fn => {
            fn.apply(this, args);
        })
    }
    on(name: string, cab: Function) {
        let fn: Array = this.list[name] || [];
        fn.push(cab)
        this.list[name] = fn
    }
}

export default new Bus()

使用

你可能感兴趣的:(Vue,前端,javascript,vue.js)