观察者和订阅-发布模式

观察者模式


class Observe {
  constructor() {
    this.events = []
  }

  subscribe(func){
    if(this.events.includes((func)))return
    this.events.push(func)
  }

  unsubscribe(func){
    const index = this.events.findIndex(func)
    if(index!==-1){
      this.events.splice(index, 1)
    }
  }

  notify(...args){
    this.events.forEach(func=>{
      func.apply(args)
    })
  }
}

// test case

const observe = new Observe()
observe.subscribe((...args)=>{
  console.log(`this is first subject `,args)
})
observe.subscribe((...args)=>{
  console.log(`this is second subject `,args)
})

observe.notify('memeda')

result

this is first subject Array(0)

this is second subject Array(0)

订阅-发布模式

result

blog updated, content is : ["this is sync task"] app.ts:51

blog updated, content is : ["microtask update"] app.ts:51

blog updated, content is : ["requestAnimationFrame update"] app.ts:51

blog updated, content is : ["macrotask update"] app.ts:73

times up, unsubscribe result is : true

Last updated

Was this helpful?