前端手写(七)——订阅发布模式

x33g5p2x  于2022-03-28 转载在 其他  
字(0.6k)|赞(0)|评价(0)|浏览(438)

一、写在前面
订阅发布模式在开发中用到的设计模式中还是比较常见的,下面将手写一些订阅发布模式。
二、代码

class EventEmmiter {
  constructor() {
    this.cache = {}
  }
  on(name, func) {
    if (this.cache[name]) {
      this.cache[name].push(func)
    } else {
      this.cache[name] = [func]
    }
  }
  off(name, func) {
    const tasks = this.cache[name]
    if (tasks) {
      let index = tasks.findIndex((value, index) => value === func)
      if (index >= 0) {
        tasks.splice(index, 1)
      }
    }
  }
  emit(name) {
    let tasks = this.cache[name]
    tasks.forEach(fn => fn())
  }
}

let events = new EventEmmiter()
const task1 = () => {
  console.log('task1')
}
const task2 = () => {
  console.log('task2')
}
events.on('task1', task1)
events.on('task2', task2)

setTimeout(() => {
  events.emit('task1')
},2000)

events.off('task1', task1)

相关文章