代码示例
class EventHub{
constructor(){
this.events = {}
}
on(type,handle){
this.events[type] = (this.events[type] || [] ).concat(handle)
}
emit(type,data){
this.events[type].forEach(handle=>handle(data))
}
off(type,handle){
if(!this.events[type]) return
if(!handle){
delete this.events[type]
return
}
let index = this.events[type].indexOf(fn)
if (index===-1) return
this.events[type].splice(index,1)
}
}
测试代码
let eventHub = new EventHub()
let fn1 = ()=>{console.log(1)}
let fn2 = ()=>{console.log(2)}
let fn3 = ()=>{console.log(3)}
let fn4 = ()=>{console.log(4)}
let fn5 = ()=>{console.log(5)}
eventHub.on('event',fn1)
eventHub.on('event',fn2)
eventHub.on('event',fn3)
eventHub.on('event',fn4)
eventHub.on('event',fn5)
eventHub.emit('event')
eventHub.off('event',fn2)
「@浪里淘沙的小法师」