zoukankan      html  css  js  c++  java
  • javaScript设计模式(一)观察者模式

    哈哈。。写了一个钟,一点一点加功能。
    1
    function Publisher(){ 2 this.subscribers = []; //存储订阅者 3 this.news = []; //存储要发布的消息 4 } 5 //使用“推”方式:由publisher推消息给Subscribers 6 7 8 Publisher.prototype = { 9 deliver : function(data){ 10 var that = this; 11 this.subscribers.forEach(function(){ 12 that.news.forEach(function(fnElement){ 13 fnElement(data); 14 }); 15 }); 16 return this; 17 }, 18 addNew : function(fn){ 19 this.news.push(fn); 20 return this; 21 } 22 23 }; 24 function Subscriber(){ 25 //使用"推",订阅者没必要保存发布者。只要发布者保存订阅者就可以了 26 // this.publishers = []; 27 } 28 Subscriber.prototype = { 29 subscribe : function(publisher){ 30 publisher.subscribers.push(this); 31 // this.publishers.push(publisher); 32 return this; 33 }, 34 unsubscribe : function(publisher){ 35 var that = this; 36 publisher.subscribers = publisher.subscribers.filter(function(element){ 37 return element !== that; 38 }); 39 40 /* this.publishers = this.publishers.filter(function(element){ 41 return element !== publisher; 42 }); 43 */ 44 return this; 45 } 46 }; 47 48 //example 49 var f1 = function (data) { 50 console.log(data + ', 赶紧干活了!'); 51 }; 52 53 var f2 = function (data) { 54 console.log(data + ',不然没饭吃!'); 55 }; 56 57 var publ = new Publisher(); 58 publ.addNew(f1).addNew(f2); 59 60 61 var subc01 = new Subscriber(); 62 subc01.subscribe(publ); 63 64 var subc02 = new Subscriber(); 65 subc02.subscribe(publ); 66 67 subc02.unsubscribe(publ); 68 69 publ.deliver('你们');
  • 相关阅读:
    Emacs 安装 jedi
    PHP+ MongoDB
    Debian 7 安装 Emacs 24.3
    在Code first中使用数据库里的视图
    Emacs安装auto-complete
    Debian 7.4 中配置PHP环境
    ASP.NET MVC 下载列表
    JDicom使用指南
    Windows常用的DOS命令
    Entity Framework问题总结
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/3275239.html
Copyright © 2011-2022 走看看