当前位置:网站首页>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)
})
}
边栏推荐
- OSPF protocol summary
- What is definition? What is a statement? What is the difference between them?
- 【cocos creator】点击按钮切换界面
- Pat class a 1030 travel plan
- Technical dry goods Shengsi mindspire innovation model EPP mvsnet high-precision and efficient 3D reconstruction
- Pat class a 1028 list sorting
- Go language foundation ----- 04 ----- closure, array slice, map, package
- 【MySQL 12】MySQL 8.0.18 重新初始化
- Go language foundation ----- 02 ----- basic data types and operators
- 输入三次猜一个数字
猜你喜欢

密西根大学张阳教授受聘中国上海交通大学客座教授(图)

Redis batch startup and shutdown script

【LeetCode】2. Valid parentheses · valid parentheses

PostGIS space function

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

HDMI2.1与HDMI2.0的区别以及转换PD信号。

Go language foundation ------ 12 ------ JSON

Docker installs MySQL and successfully uses Navicat connection

How to configure GDAL under idea

What to do after the browser enters the URL
随机推荐
技术干货|昇思MindSpore NLP模型迁移之Bert模型—文本匹配任务(二):训练和评估
C2-关于VCF文件合并的几种方法
*p++、*++p、++*p、(*p)++
Go language foundation ----- 02 ----- basic data types and operators
Go language foundation ----- 07 ----- method
Technical dry goods | some thoughts on the future of AI architecture
Go language foundation ----- 03 ----- process control, function, value transfer, reference transfer, defer function
【LeetCode】2. Valid Parentheses·有效的括号
PAT甲级 1030 Travel Plan
Quelle est la définition? Qu'est - ce qu'une déclaration? Quelle est la différence?
Go language foundation ----- 19 ----- context usage principle, interface, derived context (the multiplexing of select can be better understood here)
Go language foundation ----- 05 ----- structure
Analysis of the problems of the 12th Blue Bridge Cup single chip microcomputer provincial competition
Usage of (case, when) in PostgreSQL
Technical dry goods | Bert model for the migration of mindspore NLP model - text matching task (2): training and evaluation
Redis配置文件
Iterm2 setting
static关键字
Huawei switch console password reset, device initialization, default password
Go language foundation ----- 13 ----- file