当前位置:网站首页>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(){
//...
})
边栏推荐
- Introduction to single chip microcomputer: LED lights cycle to the left and turn on
- 徽商期货平台安全吗?办理期货开户没问题吧?
- Experience summary of slow SQL problems
- 2022 robocom world robot developer competition - undergraduate group (provincial competition) -- question 1: don't waste gold (finished)
- 4279. Cartesian tree
- Lsyncd搭建同步镜像-用Lsyncd实现本地和远程服务器之间实时同步
- 未来数据库需要关心的硬核创新
- Reentrantlock reentrant lock
- [adaptiveavgpool3d] pytorch tutorial
- celery 启动beat出现报错ERROR: Pidfile (celerybeat.pid) already exists.
猜你喜欢
![[bug solution] error in installing pycocotools in win10](/img/91/4d0ed64738656a6f406f760d6bece3.png)
[bug solution] error in installing pycocotools in win10

什么是防火墙?防火墙能发挥什么样的作用?

25. From disk to file

【AdaptiveAvgPool3d】pytorch教程

MATLAB image defogging technology GUI interface - global balance histogram

Multus of kubernetes multi network card scheme_ CNI deployment and basic use

MongoDB入门学习

2022 RoboCom 世界机器人开发者大赛-本科组(省赛)---第一题 不要浪费金币 (已完结)

Kubectl_好用的命令行工具:oh-my-zsh_技巧和窍门

24.原生磁盘的使用
随机推荐
各种Normalization的直观理解
PyTorch的自动求导
MySQL source code analysis -- data structure of index
2022 RoboCom 世界机器人开发者大赛-本科组(省赛)---第一题 不要浪费金币 (已完结)
C # exit login if there is no operation
Intuitive understanding of various normalization
【AdaptiveAvgPool3d】pytorch教程
[300 opencv routines] 238. Harris corner detection in opencv
华为无线设备配置WPA2-802.1X-AES安全策略
2022 robocom world robot developer competition - undergraduate group (provincial competition) -- question 3 running team robot (finished)
Nine key measures to maintain server security in Hong Kong
什么是防火墙?防火墙能发挥什么样的作用?
C. Recover an RBS
Android SQLite database practice
遭受DDoS时,高防IP和高防CDN的选择
JSON file editor
2022 RoboCom 世界机器人开发者大赛-本科组(省赛) CAIP 完整版题解
Use of keywords const, volatile and pointer; Assembly language and view of register status
Do you understand the working principle of gyroscope?
C# 无操作则退出登陆