当前位置: 代码迷 >> 综合 >> 观察者模式 vs 发布订阅模式
  详细解决方案

观察者模式 vs 发布订阅模式

热度:67   发布时间:2023-10-17 06:48:14.0

发布订阅模式相比观察者模式少了事件名称的定义

demo.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>观察者模式 vs 发布订阅模式</title>
</head>
<body><script>function fn1 () {console.log('fn1');}function fn2 () {console.log('fn2');}/** 观察者模式 **/// let event = new EventTarget();// event.addEventListener('myevent', fn1);// event.addEventListener('myevent', fn2);// setTimeout(() => {//     event.dispatchEvent(new CustomEvent('myevent'));// },1000);/** 发布订阅模式 **/// 依赖收集器class Dep {constructor(){this.subs = [];}addSub(sub){this.subs.push(sub);}notify(){this.subs.forEach(sub => {sub.update && sub.update(); });}}class Watcher{constructor(cb){this.cb = cb;}update(){this.cb();}}let dep = new Dep();dep.addSub(new Watcher(fn1));dep.addSub(new Watcher(fn2));setTimeout(() => {dep.notify();},1000);</script>
</body>
</html>

  相关解决方案