js mode - mode observer

// topic, receiving state change trigger each observer 
class the Subject { 
  constructor () { 
      this.state = 0 
      this.observers = [] 
  } 
  getState () { 
      return this.state 
  } 
  the setState (State) { 
      this.state = State 
      this.notifyAllObservers () 
  } 
  the attach (observer) { 
      this.observers.push (observer) 
  } 
  notifyAllObservers () { 
      this.observers.forEach (observer => { 
          observer.update () 
      }) 
  } 
} 

// observer, waiting triggered 
class the Observer { 
  constructor (name, Subject) {  
      this.name name =
      this.subject = Subject
      this.subject.attach(this)
  }
  update() {
      console.log(`${this.name} update, state: ${this.subject.getState()}`)
  }
}

// 测试代码
let s = new Subject()
let o1 = new Observer('o1', s)
let o2 = new Observer('o2', s)
let o3 = new Observer('o3', s)

s.setState(1)

 

When to change the status of the observer, the observer perform relative thing

The observer and the observed, the degree of coupling is relatively small, the code changes are not written in the viewer inside

There may be a plurality of viewers observer

 

Other scenarios

Update 1.vue the watch monitor variables

2. promise then asynchronous then there may be a plurality of viewer then FUNC. Value is updated viewer, the viewer is executed, the code is relatively small coupling. There may be more than an observer.

new new Promise FUNC = var ((Resolve, Reject) => { 
    Resolve ( 'return value'); 
}); 

func.then (function () { 
    the console.log ( "observer executed ...."); 
}) ; 

func.then (function () { 
    the console.log ( "observer executed ...."); 
});

 

Guess you like

Origin www.cnblogs.com/chenyi4/p/11413920.html