The difference between publish subscribe and observer in JavaScript

A. Observer B. Observer C. Observer D. Observer

The observer and the observed are loosely decoupled. The observed maintains a collection of observers. When there is a message, the observed sends a notification to all observers in the collection.

Code implementation ideas

  • Create an observer and an observer. The observer creates a function, both named notify, and the observer maintains a queue of observers. The created observer can be queued or removed from the queue

  • When the observer needs to be notified, the topic traverses the maintained observer queue, calling the corresponding function

Observer collection (this is a single class, but can also be incorporated into the Subject class)

class ObserverList {
  constructor(){
    this.list = []
  }
  add(fun) {
   this.list.push(fun)
  }
  remove(fun){
   const index = this.list.indexOf(fun)
   if (index < 0 || this.list.length > index) {
    return
   }
   this.list.splic(index, 1)
  }
}
Copy the code

The observer

class Observer {
  constructor(fun) {
    this.notify = fun
  }
}
Copy the code

Observed (subject)

Class Subject {constructor () {this. Observers = new ObserverList()} add (obj) {this.  { this.observers.remove(obj) } notify () { for (let i = 0; i < this.observers.list.length; i++) { this.observers.list[i].notify() } } }Copy the code

Publish and Subscribe mode Publish-subscribe pattern

Different from the observer mode, publishers do not directly notify subscribers. Publishers and subscribers do not know each other directly, and they are transmitted through a third party: message queue (center). Meanwhile, we can process data in the message center

Class EventBus {constructor() {this.eventbus = []} SUBSCRIBE (key, cb) {this.eventbus. Push ({[key]: cb }) } publish (key, params) { console.log(key, params, this.eventBus) for (let i = 0; i < this.eventBus.length; i++) { if (this.eventBus[i][key]) { this.eventBus[i][key](params) } } } } export default new EventBus()Copy the code