This is the second day of my participation in the August Text Challenge.More challenges in August

1. Publish/subscribe

  • 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

Sibling component communication process

// eventBus.js
// Event center
let eventHub = new Vue()

// ComponentA.vue
/ / publisher
addTodo: function () {
  // Publish a message (event)
  eventHub.$emit('add-todo', { text: this.newTodoText }) 
  this.newTodoText = ' '
}
// ComponentB.vue
/ / subscriber
created: function () {
  // Subscribe to messages (events)
  eventHub.$on('add-todo'.this.addTodo)
}
Copy the code

Simulate the implementation of Vue custom events

class EventEmitter {
  constructor(){
    // { eventType: [ handler1, handler2 ] }
    this.subs = {}
  }
  // Subscribe to notifications
  $on(eventType, fn) {
    this.subs[eventType] = this.subs[eventType] || []
    this.subs[eventType].push(fn)
  }
  // Issue a notification
  $emit(eventType) {
    if(this.subs[eventType]) {
      this.subs[eventType].forEach(v= >v())
    }
  }
}

/ / test
var bus = new EventEmitter()

// Register events
bus.$on('click'.function () {
  console.log('click')
})

bus.$on('click'.function () {
  console.log('click1')})// Trigger the event
bus.$emit('click')
Copy the code

1. Observer mode

  • Observer (subscriber) — Watcher

    • update(): Specific things to do when an event occurs
  • Target (publisher) — Dep

    • subsArray: Stores all observers
    • addSub()Add observer
    • notify()When an event occurs, all observers are calledupdate()methods
  • No event center

// Target (publisher)
// Dependency
class Dep {
  constructor () {
    // Store all observers
    this.subs = []
  }
  // Add an observer
  addSub (sub) {
    if (sub && sub.update) {
      this.subs.push(sub)
    }
  }
  // Notify all observers
  notify () {
    this.subs.forEach(sub= > sub.update())
  }
}

// Observer (subscriber)
class Watcher {
  update () {
    console.log('update')}}/ / test
let dep = new Dep()
let watcher = new Watcher()
dep.addSub(watcher) 
dep.notify()
Copy the code

3. Summary

  • Observer modelIs scheduled by a specific target, such as when an event is triggered,DepThe observer’s methods are called, so there is a dependency between the subscriber and publisher of the observer model
  • 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