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

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

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

  1. class EventEmmiter {
  2. constructor() {
  3. this.cache = {}
  4. }
  5. on(name, func) {
  6. if (this.cache[name]) {
  7. this.cache[name].push(func)
  8. } else {
  9. this.cache[name] = [func]
  10. }
  11. }
  12. off(name, func) {
  13. const tasks = this.cache[name]
  14. if (tasks) {
  15. let index = tasks.findIndex((value, index) => value === func)
  16. if (index >= 0) {
  17. tasks.splice(index, 1)
  18. }
  19. }
  20. }
  21. emit(name) {
  22. let tasks = this.cache[name]
  23. tasks.forEach(fn => fn())
  24. }
  25. }
  26. let events = new EventEmmiter()
  27. const task1 = () => {
  28. console.log('task1')
  29. }
  30. const task2 = () => {
  31. console.log('task2')
  32. }
  33. events.on('task1', task1)
  34. events.on('task2', task2)
  35. setTimeout(() => {
  36. events.emit('task1')
  37. },2000)
  38. events.off('task1', task1)

相关文章