Publish/subscribe
- Publish/subscribe
-
The subscriber
-
The publisher
-
The signal center
We assume there is a “signal center” that publishes a signal when a task is completed, and that other tasks can subscribe to the signal center to know when they can perform it. This is called publish-subscribe-pettern
-
Customize the publish-subscribe model in VUE.
// Event trigger
class EventEmitter {
constructor () {
// {'click': [fn1,fn2], 'change': [fn]}
this.subs = Object.create(null)}// Register events
$on(eventType, handler) {
this.subs[eventType] = this.subs[eventType] || []
this.subs [eventType].push(handler)
}
// Trigger the event
$emit(eventType) {
if(this.subs[eventType]){
this.subs[eventType].forEach(handler= > {
handler()
})
}
}
}
/ / test
let em = new EventEmitter()
em.$on('click'.() = >{
console.log('click1')
})
em.$on('click'.() = >{
console.log('click2')
})
em.$emit('click')
Copy the code
Observer model
- Observer (Subscriber) – Watcher
- Update (): Exactly what to do when an event occurs
- Target (publisher) -dep
- Subs array: Stores all observers
- AddSub (): Adds an observer
- Notify (): When an event occurs, the update() method of all observers is called
Implement observer mode
// Publisher - target
class Dep {
constructor () {
// Record all subscribers
this.subs = []
}
// Add an observer
addSub (sub) {
if(sub && sub.update) {
this.subs.push(sub)
}
}
// Issue a notification
notify () {
this.subs.forEach(sub= > {
sub.update()
})
}
}
// Subscriber - observer
class Watcher {
update(){
console.log('update')}}let dep = new Dep()
let watcher = new Watcher()
dep.addSub(watcher)
dep.notify()
Copy the code
conclusion
-
The observer mode is invoked by a specific target, for example, when an event is triggered, the Dep calls the observer’s methods, so there is a dependency between the observer mode’s subscribers and publishers
-
The publish/subscribe pattern is invoked by the unified dispatch center, so publishers and subscribers do not need to be aware of each other’s existence