1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
| <!DOCTYPE html>
<head> <title></title> <meta charset="UTF-8"> <style>
</style> </head>
<body>
<div id="test"> <div style="width: 500px; height: 300px;"> <button id="btn1">改变城市1</button> </div> <div style="width: 500px; height: 300px;"> <button id="btn2">改变城市2</button> </div>
</div> <script> // 功能:两个模块分别有两个城市切换按钮,切换其中一个,另一个模块得到通知跟着改变 ;(function(win,doc){ function Subject() { this.state = 0; //观察者列表 this.observers = [] } Subject.prototype = { getState: function() { return this.state }, setState: function(state) { this.state = state; //状态变化通知所有观察者 this.notifyAllObservers() }, notifyAllObservers:function() { this.observers.forEach(observer => { observer.update() }) }, add:function(observer) { //添加新的观察者 this.observers.push(observer) } } function Observer(subject,fn,name) { this.subject = subject; this.fn = fn; this.name = name; this.subject.add(this) } Observer.prototype.update = function() { this.fn[this.name](this.subject.getState()) } var subject = new Subject()
window.subject = subject; window.Observer = Observer; })(window,document)
;(function(win,doc){ function A() { this.btn = document.getElementById("btn1"); //默认城市ID是1 this.render(1); this.click(); //注册自己为观察者, //传入参数1:主题(写死subject就可以,已经挂在全局) //传入参数2:自己 //传入参数3:自己的渲染方法名 new Observer(subject,this,'render') } A.prototype = { click:function() { var _this = this; this.btn.addEventListener("click",function(){ //模拟接口 setTimeout(function(){ //主题变化,通知所有观察者重新渲染 subject.setState(2) },500) },false); }, render:function(id) { setTimeout(function(){ //渲染数据 console.log("A模块的ID是" + id) },500) } }
new A()
})(window,document)
;(function(win,doc){ function B() { this.btn = document.getElementById("btn2"); //默认城市ID是1 this.render(1); this.click(); new Observer(subject,this,'render') } B.prototype = { click:function() { var _this = this; this.btn.addEventListener("click",function(){ //模拟接口 setTimeout(function(){ subject.setState(3) },500) },false); }, render:function(id) { setTimeout(function(){ //渲染数据 console.log("B模块的ID是" + id) },500) } }
new B()
})(window,document)
</script> </body>
</html>
|