1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
| type subEventListT = {eventName:string,callback:(info:string)=>void} interface ISubscriber{ name:string; subEventList:subEventListT[] addSubEvent:(eventName:string,callback:()=>void)=>void; offSubEvent:(eventName:string)=>void } interface IPublisher{ name:string; data:{ message:string } }
class Subscriber implements ISubscriber{ name:string; subEventList:subEventListT[] constructor(name:string){ this.name = name; this.subEventList = [] } addSubEvent(eventName:string,callback:(info:string)=>void){ this.subEventList.push({eventName:eventName,callback:callback}) } offSubEvent(eventName:string){ this.subEventList = this.subEventList.filter((item:subEventListT)=>{ return item.eventName!=eventName }) console.log(`已取消${this.name}的${eventName}事件`,this.subEventList) } }
class Publisher implements IPublisher{ name:string; data:{message:string}; constructor(name:string,data:{message:string}){ this.name = name; this.data = data } }
class EventBus{ subscribeList:any = {} on(subObj:ISubscriber){ console.log('开始订阅'); subObj.subEventList.forEach((item:subEventListT)=>{ if(!this.subscribeList[item.eventName]){ this.subscribeList[item.eventName] = [] } this.subscribeList[item.eventName].push({name:subObj.name,callback:item.callback}) }) } emit(pubObj:IPublisher){ console.log('正在触发',pubObj.name); this.subscribeList[pubObj.name].forEach((item:any)=>{ item.callback(pubObj.data.message) }) } off(eventName:string,obj:ISubscriber){ obj.offSubEvent(eventName) this.subscribeList[eventName] = this.subscribeList[eventName].filter((item:any)=>{ return item.name!=obj.name }) console.log(this.subscribeList) } }
const xiaoming = new Subscriber('xiaoming') xiaoming.addSubEvent('squareMeter100',(info)=>{ console.log('xiaoming添加了squareMeter100订阅',info) })
xiaoming.addSubEvent('squareMeter200',(info)=>{ console.log('xiaoming添加了squareMeter200订阅',info) }) const hehe = new Subscriber('hehe'); hehe.addSubEvent('squareMeter100',(info)=>{ console.log('hehe也订阅squareMeter100',info) }) xiaoming.addSubEvent('squareMeter300',(info)=>{ console.log('xiaoming添加了squareMeter300订阅',info) }) hehe.addSubEvent('squareMeter300',(info)=>{ console.log('hehe也订阅squareMeter300',info) }) const eventbus = new EventBus() eventbus.on(xiaoming) eventbus.on(hehe)
const p = new Publisher('squareMeter100',{message:'100平米的房子'}) eventbus.emit(p)
eventbus.off('squareMeter100',xiaoming)
const p2 = new Publisher('squareMeter300',{message:'300平米的大房子'}); eventbus.emit(p2)
|