手写分发订阅模型EventEmitter 1.概要
最近发现,很多大厂商的面试问题都有手写发表订阅模型EventEmitter。 其理由是vue和react的非父子组件的通信是通过他实现的。 以下是简易版的事件发生器。
2 .代码
//订阅模型classeventemitter { constructor () }//发出事件对象,将订阅的名称和事件发送到:(click:(handle1, handle2) }this.events=} )那样存储的this.events[eventname](//1用一个名称存储多个事件函数this.events [ event name ]=[ calllbacace 在指定数组的末尾推送并保存this.events用于触发事件的方法EMIT(eventname, rest )//执行所有订阅的事件this.events [ event name ] this.events [ event name ].foreach ) f=f.f rest ()/callback ) ) if ) this.events[eventname] ) this.event name=this.event name=callback ()//订阅的事件callback ) )//绑定时删除fn将在运行时触发fn函数constfn=(.rest ) (callback.application ) rest//fn函数中的原始callback thion
const event=neweventemitter (const handle ) . pyload )=console.log ) pyload ) event.on ) click ',handle ) evendle 100
1.https://www.fed 123.com/JavaScript nodejs/4681.html
2.https://www.Jian Shu.com/p/e0575 e 17de 2a