TypeScript實現Vue數據變化監聽原理(觀察者模式)

class Common {
  private _observers: Array<Observer> = new Array<Observer>()
  private _myData: string

  get observers(): Array<Observer> {
    return this._observers
  }

  set observers(value: Array<Observer>) {
    this._observers = value
  }

  get myData(): string {
    return this._myData
  }

  set myData(value: string) {
    this._myData = value
    this.notifyAllObservers()
  }

  attach(observer: Observer): void {
    this.observers.push(observer)
  }

  notifyAllObservers(): void {
    this._observers.forEach(item => {
      item.update()
    })
  }
}

abstract class Observer {
  constructor(common: Common) {
    this.common = common
  }

  common: Common

  abstract update(): void
}

class FirstCommon extends Observer {

  constructor(common: Common) {
    super(common)
    common.attach(this)
  }

  update(): void {
    console.log('FirstCommon組件監聽到了數據改變:', this.common.myData)
  }
}

class SecondCommon extends Observer {
  constructor(common: Common) {
    super(common)
    common.attach(this)
  }

  update(): void {
    console.log('SecondCommon組件監聽到了數據改變:', this.common.myData)
  }
}

class Test {

  constructor() {
    let common = new Common()
    //組件1監聽
    new FirstCommon(common)
    //組件2監聽
    new SecondCommon(common)
    //測試修改數據
    common.myData = '測試文字'

  //  輸出結果:
  //  FirstCommon組件監聽到了數據改變:測試文字
  //  SecondCommon組件監聽到了數據改變:測試文字
  }
}

new Test()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章