当前位置:网站首页>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)
})
}
边栏推荐
- 【LeetCode】3. Merge two sorted lists · merge two ordered linked lists
- 技术干货|昇思MindSpore NLP模型迁移之Bert模型—文本匹配任务(二):训练和评估
- Redis配置文件
- s7700设备如何清除console密码
- Precautions for opensips and TLS SIP trunk docking
- yarn link 是如何帮助开发者对 NPM 包进行 debug 的?
- Go language foundation ----- 08 ----- interface
- 【MySQL 11】怎么解决MySQL 8.0.18 大小写敏感问题
- 输入三次猜一个数字
- Register keyword
猜你喜欢
An article for you to understand - Manchester code
OSPF experiment
VMware virtual machine configuration static IP
Technical dry goods | hundred lines of code to write Bert, Shengsi mindspire ability reward
LwIP learning socket (application)
Pat class a 1032 sharing
[step on the pit series] MySQL failed to modify the root password
Go language foundation ----- 08 ----- interface
PostGIS space function
【LeetCode】2. Valid Parentheses·有效的括号
随机推荐
技术干货|利用昇思MindSpore复现ICCV2021 Best Paper Swin Transformer
Go language foundation ----- 19 ----- context usage principle, interface, derived context (the multiplexing of select can be better understood here)
LwIP learning socket (application)
【LeetCode】2. Valid parentheses · valid parentheses
[MySQL 13] if you change your password for the first time after installing mysql, you can skip MySQL password verification to log in
Structure of golang
什麼是定義?什麼是聲明?它們有何區別?
Oracle queries grouped by time
PostGIS space function
Technology dry goods | luxe model for the migration of mindspore NLP model -- reading comprehension task
Huawei switch console password reset, device initialization, default password
HDMI2.1与HDMI2.0的区别以及转换PD信号。
What to do after the browser enters the URL
Technical dry goods | hundred lines of code to write Bert, Shengsi mindspire ability reward
【LeetCode】3. Merge two sorted lists · merge two ordered linked lists
创业团队如何落地敏捷测试,提升质量效能?丨声网开发者创业讲堂 Vol.03
Pat class a 1032 sharing
Harmonyos third training notes
一个实习生的CnosDB之旅
register关键字