編寫發布訂閱模式
這是更具訂閱模式寫的代碼 可以理解訂閱模式的思想
interface I {events:Map<string,Function[]>once:(event:string,callback:Function)=>void // 觸發一次on:(event:string,callback:Function)=>void // 訂閱emit:(event:string,...args:any[])=>void // 派發off:(event:string,callback:Function)=>void // 刪除監聽器
}
class Emitter implements I {events: Map<string, Function[]>;constructor(){this.events = new Map()}once(event:string,callback:Function){// 創建一個自定義函數 通過on 觸發 觸發完之后立馬通過off 回收掉const cb = (...args:any[]) => {callback(...args)this.off(event,cb)}this.on(event,cb)}off(event:string,callback:Function){const callbackList = this.events.get(event)if(callbackList){callbackList.splice(callbackList.indexOf(callback),1)} }emit(event:string,...args:any[]){const callbackList = this.events.get(event)if(callbackList){callbackList.forEach(fn=>{fn(...args)})}}on(event:string,callback:Function){// 證明存過了if(this.events.has(event)){const callbackList = this.events.get(event)callbackList && callbackList.push(callback)}else{// 否則就是第一次存this.events.set(event,[callback])}}
}const bus = new Emitter()
const fn = (b:boolean,n:number) => {console.log(1,b,n)
}bus.on('message',fn)
bus.on('message',fn)bus.emit('message',false,1)