PubAndSub 发表于 2022-11-29 | 分类于 Design Patterns 发布订阅 AddEventListens 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970class EventEmitter{ //事件处理函数集合 handlers = { //click [handler1,handler2,handler3] } //订阅 addEventListener //type click once 订阅次数 on(type,handler,once){ //当前事件类型是否存在 if(!this.handlers[type]){ //不存在则声明定义 this.handlers[type] = [] } //当前事件类型是否存在该方法 if(!this.handlers[type].includes(handler)){ //不存在则push该方法 this.handlers[type].push(handler) //是否只执行一次 handler.once = once } } once(type,handler){ this.on(type,handler,true) } //解绑 off(type,handler){ if(this.handlers[type]){ this.handlers[type] = this.handlers[type].filter(h=>{ return h !== handler }) } } trigger(type){ if(this.handlers[type]){ this.handlers[type].forEach(handler=>{ handler.call(this) if(handler.once){ this.off(type,handler) } }) } }}const ev = new EventEmitter()function handler1 (){ console.log('handler1');}function handler2 (){ console.log('handler2');}function handler3 (){ console.log('handler3' );}ev.on('test',handler1)ev.on('test',handler2)ev.on('test',handler3)ev.trigger('test')ev.trigger('test')