首页 > 编程知识 正文

发布订阅模式简单实现,发布订阅模式多消费

时间:2023-05-03 18:14:38 阅读:178188 作者:686

手写分发订阅模型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

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。