发布订阅模式:订阅者(Subscriber)把自己想订阅的事件注册(Subscribe)到调度中心(Topic),当发布者(Publisher)发布该事件(Publish topic)到调度中心,也就是该事件触发时,由调度中心统一调度(Fire Event)订阅者注册到调度中心的处理代码。
代码示例
<!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>Document</title>
<style>
#div1,#div2{
width: 200px;
height: 100px;
background-color: blanchedalmond;
margin: 10px;
}s
</style>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
<button onclick={sc()}>触发</button>
<script>
function sc() {
psc.publish('p1', Date.now());
psc.publish('p2', Date.now());
psc.publish('p1', Date.now());
}
class PubSubCenter {
topics = new Set();
publish(topic, args) {
console.log(topic, args);
if (!this.topics[topic]) {
return;
}
this.topics[topic].forEach(item => {
item.fn(item, args);
});
}
subscribe(topic, fn) {
this.topics[topic] = this.topics[topic] || [];
this.topics[topic].push({
topic,
fn
})
}
unSubScribe(topic) {
this.topics.delete(topic)
}
}
var psc = new PubSubCenter();
var a = (topics, data) => {
document.getElementById('div1').innerHTML = `${JSON.stringify(topics)} 接收事件了,数据是${data}`;
console.log(`${JSON.stringify(topics)} 接收事件了,数据是${data}`);
}
var b = (topics, data) => {
document.getElementById('div2').innerHTML = `${topics.topic} 接收事件了,数据是${data}, 订阅者2`;
console.log(`${topics.topic} 接收事件了,数据是${data}, 订阅者2`)
};
var psc1 = psc.subscribe('p1', a);
var psc2 = psc.subscribe('p2', b);
</script>
</body>
</html>
网友评论