Publish and subscribe model

  • The subscriber
  • The publisher
  • The signal center

We assume that there is a "signal center" that "publishes" a signal when a task completes, and that other tasks can "subscribe" to the signal center to know when they can start executing. This is called a publish-subscribe pattern.

  • Custom events for Vue
let vm = new Vue()
 
vm.$on('dataChange', () => {
  console.log('dataChange')
})
 
vm.$on('dataChange', () => {
  console.log('dataChange1')
})
 
vm.$emit('dataChange')
Copy the code
  • Simulate the implementation of Vue custom events
class EventEmitter { constructor() { // {click: [fn1, fn2]} this.subs = object.create (null)} $on(eventType, Handler) {this. Subs [eventType] = this. Subs/eventType | | [] this. Subs [eventType]. Push (handler)} / / trigger $emit (eventType)  { if(this.subs[eventType]) { this.subs[eventType].forEach(fn => { fn() }) } } } const 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
  • No event center

Constructor () {constructor() {this.subs = []} // Add subscriber addSub(sub) {if (sub && sub.update) { ForEach (sub => {sub.update()}) {this.subs.push(sub)}} 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 pattern is scheduled 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 pattern’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