当前位置:网站首页>Simplified understanding: publish and subscribe
Simplified understanding: publish and subscribe
2022-07-24 15:37:00 【InfoQ】
// Publisher Publisher
class Pub {
constructor() {
this.deps = [];
}
addDep(dep) {
this.deps.push(dep);
}
publish(dep) {
this.deps.forEach(item => item === dep && item.notify());
}
}
// subscriber Subscriber
class Sub {
constructor(val) {
this.val = val;
}
update(callback) {
callback(this.val)
}
}
// Dispatching center
class Dep {
constructor(callback) { // The core is this callback function ;
this.subs = [];
this.callback = callback;
}
addSub(sub) {
this.subs.push(sub);
}
notify() {
this.subs.forEach(item => item.update(this.callback));
}
}
let pub = new Pub() // Instantiate a publisher
// Instantiate a dispatch center , Pass in a function for processing data ;
const dep1 = new Dep((data) =>
console.log(' This is the dispatch center , Let me deal with the message first , Then send it to ===》》》', data))
let sub1 = new Sub(" subscriber 1") // Instantiate subscribers 1
let sub2 = new Sub(" subscriber 2") // Instantiate subscribers 2
pub.addDep(dep) // The publisher binds to the dispatching center
dep.addSub(sub1) // Add subscriber to dispatch center 1
dep.addSub(sub2) // Add subscriber to dispatch center 2
pub.publish(dep) // The publisher pushes the message to the dispatcher
// This is the dispatch center , I'll deal with the message first subscriber 1
// This is the dispatch center , I'll deal with the message first subscriber 2
- Publishers need to have two methods , Bind dispatcher Dep, Push the message to the dispatcher ;
- The dispatcher also has two methods , Binding subscribers Sub, Push messages to subscribers ;
- Subscribers have a way , Execute function ;
function weatherWarning(weatherStatus){
if(weatherStatus==='warning'){ // Bad weather
buildingsite.stopwork() // Work stoppage
ships.mooring() // The ship is suspended
tourists.canceltrip() // The tour is cancelled
}
}
weatherWarning("warning") // Issue a bad weather notice


const EventEmit = function() { // Dispatching center
this.events = {};
this.on = function(name, cb) { // Bind subscriber
if (this.events[name]) {
this.events[name].push(cb); // Support the same subscriber to perform multiple things
} else {
this.events[name] = [cb];
}
};
this.trigger = function(name, ...arg) { // Send a message
if (this.events[name]) {
this.events[name].forEach(eventListener => {
eventListener(...arg);
});
}
};
};
let weatherEvent = new EventEmit() // Instantiate a dispatch center
weatherEvent.on('warning', function () { // Bind the relation of publishing notification
// buildingsite.stopwork()
console.log('buildingsite.stopwork()')
})
weatherEvent.on('warning', function () { // Bind the relation of publishing notification
// ships.mooring()
console.log('ships.mooring()')
})
weatherEvent.on('warning', function () { // Bind the relation of publishing notification
// tourists.canceltrip()
console.log('tourists.canceltrip()')
})
weatherEvent.trigger('warning') // Release the news
class Subject{// Observed
constructor(){
this.observers=[]
}
add(observer){
this.observers.push(observer)
}
notify(weatherStatus){
this.observers.forEach(i=>i(weatherStatus))
}
}
let sub = new Subject()
sub.add((reason)=>{
// buildingsite.stopwork()
console.log(' Work stoppage , Because of the weather :',reason)
})
sub.add((reason)=>{
// ships.stopwork()
console.log(' The ship is suspended , Because of the weather :',reason)
})
sub.add((reason)=>{
// tourists.canceltrip()
console.log(' The tour is cancelled , Because of the weather :',reason)
})
sub.notify("warning") // sub Release the news
// Work stoppage , Because of the weather : warning
// The ship is suspended , Because of the weather : warning
// The tour is cancelled , Because of the weather : warning
element.addEventListener('click', function(){
//...
})
边栏推荐
猜你喜欢
![[quantitative test]](/img/df/f2d8b252169213af340f3e535bddef.png)
[quantitative test]

Android section 13 detailed explanation of 03sqlite database

26.文件使用磁盘的代码实现

Fine tune layoutlm V3 for bill data processing and content recognition

华为无线设备配置WAPI-证书安全策略

matlab图像去雾技术GUI界面-全局平衡直方图

Personal practical experience: Data Modeling "whether account data belongs to dimension or account domain"

C# - partial 关键字

华为无线设备配置WPA2-802.1X-AES安全策略

Force button 31. Next arrangement -- double finger needling
随机推荐
Cloud development standalone image Jiugongge traffic main source code
kubernetes多网卡方案之Multus_CNI部署和基本使用
iptables常用命令小清单
[adaptiveavgpool3d] pytorch tutorial
基于Lambert函数的时滞系统稳定性研究
[tf.keras]: a problem encountered in upgrading the version from 1.x to 2.x: invalidargumenterror: cannot assign a device for operation embedding_
Huawei wireless device configuration wpa2-802.1x-aes security policy
哈夫曼树(最优二叉树)
Personal practical experience: Data Modeling "whether account data belongs to dimension or account domain"
JUC source code learning note 3 - AQS waiting queue and cyclicbarrier, BlockingQueue
Research on stability of time-delay systems based on Lambert function
报错【项目报错】
未来数据库需要关心的硬核创新
各种Normalization的直观理解
Still using listview? Use animatedlist to make list elements move
IP protocol - network segment division
25. From disk to file
接参处理和@Param
【量化测试】
SQL row to column, column to row