当前位置:网站首页>JS Improvement: Handwritten Publish Subscriber Model (Xiaobai)
JS Improvement: Handwritten Publish Subscriber Model (Xiaobai)
2022-08-01 21:03:00 【The..Fuir】
//Take CSDN as an examplefunction pubSub(){//Store the array of user information that CSDN has followed methis.accounts=[];}//subscribe SubscribepubSub.prototype.subscribe=function(key,callback){//key: my accountif(!this.accounts[key]){//This store stores which users have followed me as a CSDN user, and if there is anythis.accounts[key]=[]}//callback is equivalent to the user, put this user into this follow me arraythis.accounts[key].push(callback)}//publish publishpubSub.prototype.publish=function(key,content){//Notify everyone who follows my accountthis.accounts[key].forEach(user=>{user(content);})}//remove removes people who follow my accountpubSub.prototype.remove=function(key,callback){// Determine whether there is attention to me, that is, whether there is an event of type type in the message queue, if not, return directlyif (!this.accounts[key])return; //Break out of the loop directly// Determine if there is a callback parameterif (!callback) { // If there is no callback, delete the entire eventthis.accounts[key] = undefined;}else{// If there is a callback, just delete the callback message (filter out this method)this.accounts[key] = this.accounts[key].filter((item) => item !== callback);}}//Intermediate agent, manage alllet pubsub=new pubSub();//subscription//Dalong pays attention to me, which is equivalent to binding an event to Dalong. When I publish an article, I will notify Dalong.let a=function follow1(content){console.log(content,'Dalong received a message from my published article');}pubsub.subscribe('my account', a)let b=function follow2(content){console.log(content,'Xiaolong received a message from my published article');}pubsub.subscribe('my account',b)let c=function follow3(content){console.log(content,'Dalong received a message from my published article');}pubsub.subscribe('my account',c);// remove people who follow mepubsub.remove('My Account',c);//release//Information release, only people who follow my account will push the information of my newly published articles in real timepubsub.publish('My Account', 'Happy Mid-Autumn Festival');// key is equivalent to an account, and callback is equivalent to the person who follows this account// pubsub.publish(key,callback);
class Observer {constructor() {this.message = {}; // message queue}// Delegate something to this person1, call person1's '$on' method// add content '$on' to message queue$on(type, callback) {// Determine whether there is this attribute (time type)if (!this.message[type]) {// If there is no such property, initialize an empty arraythis.message[type] = [];}// If there is this property, push a new callback after himthis.message[type].push(callback);}// delete the contents of the message queue$off(type, callback) {// Determine whether there is a subscription, that is, whether there is an event of type type in the message queue, if not, return directlyif (!this.message[type])return;// Determine if there is a callback parameterif (!callback) { // If there is no callback, delete the entire eventthis.message[type] = undefined;}// If there is a callback, just delete the callback message (filter out this method)this.message[type] = this.message[type].filter((item) => item !== callback);}// Trigger the contents of the message queue$emit(type) {// Determine if there is a subscriptionif(!this.message[type]) return;// If there is a subscription, do a poll for the 'type' event (for loop)this.message[type].forEach(item=>{//Execute the callback function of each message one by oneitem();})}}function handlerA() {console.log('handlerA');}function handlerB() {console.log('handlerB');}function handlerC() {console.log('handlerC');}// use the constructor to create an instanceconst person1 = new Observer();person1.$on('buy', handlerA);person1.$on('buy', handlerB);person1.$on('buy', handlerC);//delete handlerC informationperson1.$off('buy',handlerC);console.log('person1 :>> ', person1);//Trigger buy eventperson1.$emit('buy');
边栏推荐
猜你喜欢

Hiking, cured my mental internal friction

4.1 配置Mysql与注册登录模块

JS提升:如何中断Promise的链式调用

WeChat applet cloud development | personal blog applet
![漏洞分析丨HEVD-0x6.UninitializedStackVariable[win7x86]](/img/37/09ab9b5a490c6ab9bc7991ecc4c8f4.png)
漏洞分析丨HEVD-0x6.UninitializedStackVariable[win7x86]
Godaddy域名解析速度慢问题以及如何使用DNSPod解析解决

技能大赛训练:A部分加固题目

使用员工管理软件,解锁人力生产力新水平,提高人力资源团队灵活性

2022年秋招,软件测试开发最全面试攻略,吃透16个技术栈

R语言 线性回归的有关方法
随机推荐
C陷阱与缺陷 第7章 可移植性缺陷 7.11 可移植性问题的一个例子
封装一个管理 url 状态的 hook
Common pits in the Go language
R语言 数据的关系探索
Pytorch框架学习记录12——完整的模型训练套路
移植MQTT源码到STM32F407开发板上
C陷阱与缺陷 第7章 可移植性缺陷 7.10 首先释放,然后重新分配
[译] 容器和 Kubernetes 中的退出码完整指南
pytest:开始使用
进行交互或动画时如何选择Visibility, Display, and Opacity
Godaddy域名解析速度慢问题以及如何使用DNSPod解析解决
Multithreaded producers and consumers
Buttons with good user experience should not have hover state on mobile phones
Goroutine Leaks - The Forgotten Sender
系统收集集
latex paper artifact -- server deployment overleaf
WeChat applet cloud development | personal blog applet
STAHL touch screen repair all-in-one display screen ET-316-TX-TFT common faults
360借条安全专家:陌生微信好友不要轻易加贷款推广多是诈骗
Digital twin Beijing the imperial palace, yuan universe is the process of tourism

