我的代码:eventBus的实现

357 阅读1分钟
class EventList{
    constructor(){
        this.eventProto = {}
    }
    on(key,fn){
        if(!this.eventProto.hasOwnProperty(key)){
            this.eventProto[key] = []
        }
        this.eventProto[key].push(fn)
        return this
    }
    emit(key,...args){
        try{
            if(this.eventProto[key].length){
            this.eventProto[key].map(fn=>{
                fn.apply(this,args)
            })
            }
        }catch{
            console.error('没定义的event',key)
        }
    }
    off(key){
        try{
            delete this.eventProto[key]
        }catch{
            console.error('没定义的event无法卸载',key)
        }
    }
    once(key,fn){
        const onceFn =(...args)=>{
            this.off(key);
            fn.apply(this,args)
        }
        this.on(key,onceFn)
    }
}
const add = (a,b)=>console.log(a+b)
const log =(...args) => console.log(args)
const event = new EventList()
//on监听参数,emit执行参数,off卸载参数
event.on('add',add)
event.on('log',log)
event.emit('log','hi~') 
event.emit('add',1,2)
event.emit('log','hi~')
event.off('add')
event.emit('add',1,2)
event.once('once',add)
event.emit('once',1,2)
event.emit('once',1,2)
event.emit('once',1,2)