观察者模式

 1 <script>
 2     var Paper = function() {
 3         this.customers = [];
 4     };
 5     
 6     Paper.prototype.sendPaper = function(data) {
 7         for(var i = 0, len = this.customers.length; i < len; i++) {
 8             this.customers[i].receive(data);
 9         }
10     };
11 
12     var Customer = function(param) {
13         this.name = param.name;
14     };
15     
16     Customer.prototype.subscribe = function(paper) {
17         var customers = paper.customers;
18         var isExist = false;
19         for(var i = 0, len = customers.length; i < len; i++){ 
20             if(customers[i] === this){
21                 isExist = true;
22                 break;
23             }
24         }
25         
26         if(!isExist) {
27             customers.push(this);
28         }
29         
30         return this;
31     };
32     
33     Customer.prototype.receive = function(data) {
34         console.log(this.name + "接收了 " + data.paperName);
35     };
36     
37     var Beijingpaper = new Paper();
38     var Tianjingpaper = new Paper();
39     var Shanghaipaper = new Paper();
40     
41     var Jim = new Customer({name: "Jim"});
42     var Bily = new Customer({name: "Bily"});
43     
44     Jim.subscribe(Beijingpaper).subscribe(Tianjingpaper);
45     Bily.subscribe(Shanghaipaper).subscribe(Tianjingpaper);
46     
47     Shanghaipaper.sendPaper({paperName:"shagnhai"});
48     Tianjingpaper.sendPaper({paperName:"Tianjing"});
49     Beijingpaper.sendPaper({paperName:"beijing"});
50     
51 </script>

 

 1 <script>
 2     function Click() {
 3         this.handlers = [];
 4     }
 5     
 6     Click.prototype = {
 7         subscribe: function(fn) {
 8             this.handlers.push(fn);
 9         },
10         unsubscribe: function(fn) {
11             this.handlers = this.handlers.filter(function(item) {
12                 if(item !== fn) {
13                     return item;
14                 }
15             });
16         },
17         fire: function(o, thisObj) {
18             var scope = thisObj || window;
19             this.handlers.forEach(function(item) {
20                 item.call(scope, o);
21             });
22         }
23     };
24     
25     var log = (function() {
26         var log = "";
27         return {
28             add: function(msg) {log += msg + "
";},
29             show: function() { alert(log); log = "";}
30         };
31     })();
32     
33     function run() {
34         var clickHandler = function(item) {
35             log.add("fired: " + item);
36         };
37         
38         var click = new Click();
39         
40         click.subscribe(clickHandler);
41         click.fire("event #1");
42         
43         log.show();
44     }
45     run();
46 </script>
View Code
原文地址:https://www.cnblogs.com/daishuguang/p/3674997.html