Interviewer must ask series: handwritten publish subscribe mode and observer mode

catalogue

preface

1. Publish subscribe mode

definition

Handwritten publish subscribe mode

2. Observer mode

definition

Handwriting observer mode

3. The fundamental difference between the two

preface

Publish subscriber mode and observer mode are two design modes. They are the same in essence, but there are also differences. There are different application scenarios in Vue. Second, the foundation of ue responsive data, and the knowledge points about data proxy and data hijacking can be referred to this article I learned the principle tiktok and data hijacking in Vue data gap. czjl6886's blog - CSDN blog

1. Publish subscribe mode

definition

There is a "signal center". When a task is completed, publish a signal to the signal center, and other tasks subscribe to the signal to the information center, so as to know when they can start execution, that is, publish subscribe mode.

Handwritten publish subscribe mode

In the pseudo code: emit triggers the event, publishes the data, and on subscribes to the event and receives the data

<script>
    class EventEmitter{
      constructor(){
        // Initialize to an empty new object
        // Create one on vm_ Events object, which is used to store events
        this._events=Object.create(null)
      }
      // Listen to the event and obtain the data provided after the event triggered by emit
      on(event,fn){
        // If it is an array, loop to listen for array events
        if(Array.isArray(event)){
          event.forEach(item => {
            this.on(item,fn)
          })
        }else{
          (this._events[event] || (this._events[event]=[])).push(fn)
        }
      }
      // Close event binding
      off(event,fn){
        // If the parameter is empty, all event bindings will be closed
        if(!arguments.length){
          // Reset to an empty object
          this._events = Object.create(null)
          return
        }
        // If the incoming event does not emit, return; Emit is used to trigger events
        if(!this._events[event]) return
        // If no callback function is passed in, all callback functions bound to this event will be removed by default,
        // Otherwise, remove the same callback as fn
        if(!fn){
          this._events[event] = []
          return
        }else{
          // this._events[event] refers to the same data type as cbs
          const cbs = this._events[event]
          let i = this._events[event].length
          while(i--){
            if(cbs[i] === fn || cbs[i].fn === fn){
              cbs.splice(i,1)
              continue
            }
          }
        }
      }
      // The custom event is triggered only once
      once(event,fn){
        const on=()=>{
          // Destroy the event at the first execution
          this.off(event,on)
          fn.apply(this,arguments)
        }
        on.fn = fn
        this.on(event,on)
      }
      // Trigger event and provide data
      emit(event,...args){
        const cbs=this._events[event]
        if(cbs){
          cbs.forEach(fn => {
            fn.apply(this,args)
          })
        }
      }
    }
    const initEvent = new EventEmitter()
    function fnTest(value){
      console.log("This is a event" + value)
    }
    // Bind click event and callback function fnTest
    initEvent.on("click",fnTest)

    initEvent.once("click",fnTest)

    initEvent.emit("click","This parameter refers to emit Data to be transmitted by the triggered event")
    // Close event binding
    initEvent.off("click")

  </script>

2. Observer mode

definition

When an event occurs, the observer (subscriber, watcher) executes the update () method to complete the corresponding operation; The observed target (publisher, Dep) uses the array subs to store all observers. You can also use addSub() to add new observers. When an event occurs, call the update() method of all observers.

Handwriting observer mode

<script>
    // Observed target, i.e. Publisher: Dep
    class Dep{
      constructor(){
        // Record all observers, i.e. subscribers
        this.subs = []
      }
      // Add a new observer
      addSub(sub){
        // If the subscriber exists and has an update method, it is added to the subs array
        if(sub && sub.update){
          this.subs.push(sub)
        }
      }
      // Remove observer
      removeSub(sub) {
        if (this.subs.length) {
          let index = this.indexOf(sub)
          if (index > -1) {
            this.sub.splice(index, 1)
          }
        }
      }
      // Publish update notification
      notify(){
        this.subs.forEach(item =>{
          item.update()
        })
      }
    }

    // The observer is the subscriber
    class Watcher{
      update(){
        console.log("****Update relevant data****")
      }
    }

    let dep = new Dep
    let watcher1 = new Watcher
    let watcher2 = new Watcher

    // Add a new observer
    dep.addSub(watcher1)
    dep.addSub(watcher2)
    dep.removeSub(watcher2)
    // release
    dep.notify()

  </script>

3. The fundamental difference between the two

Publish subscribe mode: it is called by a unified dispatching center, and the publisher and subscriber do not need to know the existence of each other;

Observer mode: scheduled by a specific target. For example, when an event is triggered, Dep will call the methods of observers related to the event stored in the array. Therefore, there is a dependency between subscribers and publishers in observer mode;

Keywords: Front-end Vue Vue.js Interview

Added by martins on Sat, 05 Mar 2022 01:13:24 +0200