Two constructors are required to implement this

  1. Creating an observer a. requires an id B. requires a skill
  2. Create an observed (a) property, its own state (b) queue, which records all observers (c). Method, I can set my state, and when I click that I need to change, I’m going to go to this method and change state D. Method, add observer e. method, delete observer
// Observer constructor
class Observer  {
    constructor(name,fn=() => {}) {
        this.name = name
        this.fn = fn
    }
}
// Create two observers
const bzr = new Observer('Head teacher'.(state) = > {console.log('should be'+ state+"Get your father.")})
const xz = new Observer('the headmaster'.() = > {console.log('Scolding the head teacher')})

class Subject {
    constructor(status) {
        // Record your status
        this.status = status
        // Array to hold people watching me
        this.observers = []
    }
    setstate (val) {
        this.status = val
        
        // All observer abilities need to trigger
        this.observers.forEach(item= > {
            item.fn(val)
        })

    }
    addobserve(observer) {
        // If the observer already exists, do not add it
        // some() find() indexOf() filter()
        const res = this.observers.some(obs= > obs===observer)
        if(! res) {this.observers.push(observer)
        }
        
    }
}

// Create an observed
const xiaomin = new Subject('learning')

// Add an observer to Xiaoming
xiaomin.addobserve(bzr)
xiaomin.addobserve(xz)

xiaomin.setstate('Play games')
Copy the code