observer pattern in javascript

本来是想放在google的blog上面,试用一下的。没想到在发布的时候google的编辑器不允许包含有脚本标签等,还是放在这儿吧。以后有时间自己好好写一个blog系统。

 1 <script type="text/javascript">
 2     window.onload=function(){
 3         var b=new B();
 4 
 5         var a = new A();
 6         a.i = "the 1st object will be show"
 7         b.attObj(a);//object a be attach
 8 
 9         var a1 = new A();
10         a1.i = "the 2nd object will be show"
11         b.attObj(a1);//object b be attach
12 
13         //invoke method of object b
14         b.m1();
15     }
16     function A(){  //class A be defined
17         this.i=1;
18         var _this=this;
19         this.m1=function(){
20              alert(this.i);
21         }
22     }
23 
24     function B(){
25         this.extObj = [];
26         this.attObj = function(obj){
27             this.extObj.push(obj);
28         }
29         this.m1=function(){
30             //when all operation of object B be finished,all subscriber will be notify.
31             for(var i=0;i<this.extObj.length;i++){
32                 this.extObj[i].m1();
33             }
34         }
35     }
36 
37     </script>


原文地址:https://www.cnblogs.com/sxlfybb/p/1310131.html