当前位置:网站首页>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)
})
}
边栏推荐
- 微软安全响应中心
- Introduction of novel RNA based cancer therapies
- Research shows that breast cancer cells are more likely to enter the blood when patients sleep
- Redis查看客户端连接
- UA camouflage, get and post in requests carry parameters to obtain JSON format content
- Getting started with minicom
- Docker installs MySQL and successfully uses Navicat connection
- 【cocos creator】点击按钮切换界面
- Go language foundation ----- 01 ----- go language features
- Go language foundation ----- 19 ----- context usage principle, interface, derived context (the multiplexing of select can be better understood here)
猜你喜欢

EtherCAT state machine transition (ESM)

Technical dry goods | thinking about the unification of dynamic and static diagrams of AI framework

Go language foundation ----- 02 ----- basic data types and operators

What is a data type? What is the use of data types?

Robots protocol

Go language foundation ----- 15 ----- reflection

【LeetCode】2. Valid parentheses · valid parentheses

Research shows that breast cancer cells are more likely to enter the blood when patients sleep

PostGIS space function

Technical dry goods | some thoughts on the future of AI architecture
随机推荐
Static keyword
What to do after the browser enters the URL
【LeetCode】2. Valid Parentheses·有效的括号
EtherCAT state machine transition (ESM)
[at] abc 258G - Triangle 三元組可達-暴力
[MySQL 14] use dbeaver tool to remotely backup and restore MySQL database (Linux Environment)
Huawei switch: configure Telnet, SSH and web access
【LeetCode】2. Valid parentheses · valid parentheses
How does yarn link help developers debug NPM packages?
技术干货|关于AI Architecture未来的一些思考
Huawei switch console password reset, device initialization, default password
技术干货|昇思MindSpore可变序列长度的动态Transformer已发布!
Worldview satellite remote sensing image data / meter resolution remote sensing image
华为S5700交换机初始化和配置telnet,ssh用户方法
Technical dry goods | hundred lines of code to write Bert, Shengsi mindspire ability reward
微软安全响应中心
【LeetCode】3. Merge Two Sorted Lists·合并两个有序链表
OSPF protocol summary
Huawei switches are configured with SSH login remote management switches
Pat grade a 1027 colors in Mars