type BusClass = {
on: (name:string, callback:Function) => void,
emit: (name:string, ...args: Array<any>) => void,
off: (name:string, callback: Function) => void,
once: (name: string, callback: Function) => void,
}
type ParamsKey = string | number | symbol
type List = {
[key: ParamsKey]: Array<Function>
}
class Bus implements BusClass {
list: List
constructor () {
this.list = {}
}
emit(name:string, ...args: any[]) {
let eventName: Array<Function> = this.list[name]
if (eventName) {
eventName.forEach(fn => {
fn.apply(this, args)
})
} else {
console.log('该事件未监听')
}
}
on(name:string, callback:Function) {
const callbackList: Array<Function> = this.list[name] || []
callbackList.push(callback)
this.list[name] = callbackList
}
off(name:string, callback: Function) {
let eventName:Function[] = this.list[name]
if (eventName && callback) {
let idx = eventName.findIndex(fn => fn === callback)
eventName.splice(idx, 1)
} else {
console.log('该事件未监听')
}
}
once(name: string, callback: Function) {
let decor = (...args: any[]) => {
callback.apply(this, args)
this.off(name, decor)
}
this.on(name, decor)
}
}
export default new Bus()
使用
const bus = new Bus()
bus.on('testFn', (...arg: any[]) => {
console.log(arg, '------')
})
bus.emit('testFn', 'zs', 18)
结果
