首页 > 代码库 > javascript设计模式之观察者模式
javascript设计模式之观察者模式
观察者模式又称发布/订阅模式 publish/subscribe
它是一种一对多的关系,让多个观察者对象同时监听某一主题对象,这个主题对象的状态发生变化时就会通知所有的观察者对象,使得他们能够自动更新自己。
1 function msgBus(){ 2 3 var msgMap = {}; // internal message bus 4 var instance = {}; 5 6 7 /** 8 * @function subscribe 9 * @description subscribe message listener.10 * @param msgType {string} - message type to be listen.11 * @param handler {function} - handler function when the message sent.12 * @instance13 */14 instance.subscribe = function(msgType,handler){15 if(msgType == null){16 console.error("Message type is null");17 return instance;18 }19 if(handler == null){20 console.error("handler is null");21 return instance;22 }23 var subscribeArray = msgMap[msgType];24 if(subscribeArray == null){25 subscribeArray = new Array();26 msgMap[msgType] = subscribeArray;27 }28 if(subscribeArray.indexOf(handler) < 0){29 subscribeArray.push(handler);30 }31 return instance;32 }33 34 /**35 * @function unsubscribe36 * @description unsubscribe message listener.37 * @param msgType {string} - message type to be unsubscribe.38 * @param handler {function} - handler function to be removed.39 * @instance40 */41 42 instance.unsubscribe = function(msgType,handler){43 var subscribeArray = msgMap[msgType];44 if(subscribeArray != null){45 var index = subscribeArray.indexOf(handler);46 if(index > 0){47 subscribeArray.splice(index,1);48 }49 }50 51 return instance;52 }53 54 55 /**56 * @function publish57 * @description publish message.58 * @param msgType {string} - message type to be published.59 * @param data {object} - message data.60 * @instance61 */62 instance.publish = function(msgType,data){63 var subscribeArray = msgMap[msgType];64 if(subscribeArray == null){65 return;66 }67 for(var i=0;i<subscribeArray.length;i++){68 try{69 subscribeArray[i](data);70 }catch(e){71 console.error("Error when sending Message: "+msgType);72 }73 }74 75 return instance;76 }77 78 return instance;79 }
测试一下:
var instance = msgBus();instance.subscribe("subscribe",function(data){console.log("this is "+data)});instance.publish("subscribe","cangjingkong"); // this is cangjingkong
javascript设计模式之观察者模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。