标签:练习 lis har his html 设计模式 http es6 char
1、JS ES6 定义类,并包含两个方法:subscribe(订阅)、publish(发布)。
class PubJs {
constructor () {
// 订阅名称列表
this.event_list = {};
}
// 订阅
subscribe (eventName, callback) {
}
// 发布
publish (eventName, ...args) {
}
}
2、编写订阅者基础逻辑:
class PubJs {
constructor () {
// 订阅名称列表
this.event_list = {};
}
// 订阅
subscribe (eventName, callback) {
if (this.event_list[eventName]) {
this.event_list[eventName].push(callback);
} else {
this.event_list[eventName] = [callback];
}
}
// 发布
publish (eventName, ...args) {
}
}
3、编写发布者基础逻辑:
class PubJs {
constructor () {
// 订阅名称列表
this.event_list = {};
}
// 订阅
subscribe (eventName, callback) {
if (this.event_list[eventName]) {
this.event_list[eventName].push(callback);
} else {
this.event_list[eventName] = [callback];
}
}
// 发布
publish (eventName, ...args) {
if (this.event_list[eventName]) {
this.event_list[eventName].map(cb => cb(...args));
}
}
}
4、本地验证:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>练习发布-订阅模式</title>
<script src="./pub.js"></script>
</head>
<body>
<div>
练习发布-订阅模式
</div>
<script>
const pubSub = new PubJs();
// A订阅了SMS事件(A只关注SMS本身,而不关心谁发布这个事件)
pubSub.subscribe(‘SMS‘, console.log);
// B订阅了SMS事件
pubSub.subscribe(‘SMS‘, console.log);
// C发布了SMS事件(C只关注SMS本身,不关心谁订阅了这个事件)
pubSub.publish(‘SMS‘, ‘I published `SMS` event‘);
setTimeout(() => {
pubSub.publish(‘SMS‘, ‘I published `SMS` again‘);
}, 5000)
</script>
</body>
</html>
标签:练习 lis har his html 设计模式 http es6 char
原文地址:https://www.cnblogs.com/JockerM/p/12055567.html