当前位置:网站首页>JS to implement publish and subscribe
JS to implement publish and subscribe
2022-07-03 07:52:00 【Peter Sue】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Simple publish subscription </title>
</head>
<body>
<!-- In publish and subscribe mode , There are two objects , One is the publisher of the event , One is the subscriber . Brief ideas : 1. Create an object ( Cache list ) 2.on Method is used to call the callback function fn Are added to the cache list 3.emit Method to get arguments The first one in the class is key, according to key Value to execute the function in the corresponding cache list 4.remove The method can be based on key Value unsubscribe -->
<script> let event = {
list: {
}, // Subscription events on(key, fn) {
// If there is no corresponding... In the object key value // That means you haven't subscribed to // Then give it to key Create a cache list if (!this.list[key]) {
this.list[key] = [] } // Add the function to the corresponding key In the cache list this.list[key].push(fn) }, // Release events emit() {
// The first parameter corresponds to key value , Use the array directly shift Method take out let key = [].shift.call(arguments), fns = this.list[key]; // If there is no function in the cache list, it returns false if (!fns || fns.length === 0) {
return false } // Traverse key Value corresponds to the cache list // The method of executing functions in turn fns.forEach(fn => {
fn.apply(this, arguments) }) }, // Unsubscribe event remove(key, fn) {
console.log(' Unsubscribe event '); let fns = this.list[key]; // If there are no functions in the cache list , return false if (!fns) return false; // If the corresponding function is not passed // Will be key The functions in the cache list corresponding to the value are cleared if (!fn) {
fns && (fns.length = 0); } else {
// Traverse the cache list , Look at the incoming fn With which function // If it is the same, delete it directly from the cache list fns.forEach((cb, i) => {
if (cb == fn) {
fns.splice(i, 1) } }) } } } function cat() {
console.log(' I'm a cat '); } function dog() {
console.log(' I'm Wangcai '); } event.on('pet', data => {
console.log(data); }); event.on('pet', cat); event.on('pet', dog); // Cancel dog Method event.remove('pet', dog); // Release event.emit('pet', [' Persian cat 1', ' Pipa dog 1']) </script>
</body>
</html>
// The trigger event has two parameters ( Event name , Parameters )
emit (type, ...params) {
// If the event is not registered, an error is thrown
if (!(type in this.handlers)) {
return new Error(' The event is not registered ')
}
// Convenience trigger
this.handlers[type].forEach(handler => {
handler(...params)
})
}
边栏推荐
- Differences between tp3.2 and tp5.0
- 华为S5700交换机初始化和配置SSH和TELNET远程登录方法
- LwIP learning socket (application)
- opensips与对方tls sip trunk对接注意事项
- C2-关于VCF文件合并的几种方法
- Project experience sharing: Based on mindspore, the acoustic model is realized by using dfcnn and CTC loss function
- Structure of golang
- Analysis of the ninth Blue Bridge Cup single chip microcomputer provincial competition
- Technical dry goods Shengsi mindspire dynamic transformer with variable sequence length has been released!
- An article for you to understand - Manchester code
猜你喜欢

Docker installs MySQL and successfully uses Navicat connection

HarmonyOS第三次培训笔记

Unity XR实现交互(抓取,移动旋转,传送,射击)-Pico
![[MySQL 14] use dbeaver tool to remotely backup and restore MySQL database (Linux Environment)](/img/38/3435d353e50b19fe09c8ab9db52204.png)
[MySQL 14] use dbeaver tool to remotely backup and restore MySQL database (Linux Environment)

Partage de l'expérience du projet: mise en œuvre d'un pass optimisé pour la fusion IR de la couche mindstore

Getting started with minicom

Redis batch startup and shutdown script

技术干货|昇思MindSpore NLP模型迁移之Roberta ——情感分析任务

Pat class a 1032 sharing

*p++、*++p、++*p、(*p)++
随机推荐
什么是数据类型?数据类型有什么用?
Project experience sharing: Based on mindspore, the acoustic model is realized by using dfcnn and CTC loss function
Go language foundation ------ 14 ------ gotest
Usage of (case, when) in PostgreSQL
Harmonyos third training notes
【LeetCode】4. Best Time to Buy and Sell Stock·股票买卖最佳时机
[MySQL 14] use dbeaver tool to remotely backup and restore MySQL database (Linux Environment)
Go language foundation ----- 18 ----- collaboration security, mutex lock, read-write lock, anonymous lock, sync Once
OSPF experiment
Technical dry goods Shengsi mindspire operator parallel + heterogeneous parallel, enabling 32 card training 242 billion parameter model
基于RNA的新型癌症疗法介绍
【MySQL 14】使用DBeaver工具远程备份及恢复MySQL数据库(Linux 环境)
Static keyword
PHP wechat red packet grabbing algorithm
VMware virtual machine configuration static IP
Analysis of the ninth Blue Bridge Cup single chip microcomputer provincial competition
Professor Zhang Yang of the University of Michigan is employed as a visiting professor of Shanghai Jiaotong University, China (picture)
When did you find out that youth was over
哪一刻你才发现青春结束了
[untitled]