javascript设计模式之观察者模式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 * @instance 13 */ 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 unsubscribe 36 * @description unsubscribe message listener. 37 * @param msgType {string} - message type to be unsubscribe. 38 * @param handler {function} - handler function to be removed. 39 * @instance 40 */ 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 publish 57 * @description publish message. 58 * @param msgType {string} - message type to be published. 59 * @param data {object} - message data. 60 * @instance 61 */ 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设计模式之观察者模式的主要内容,如果未能解决你的问题,请参考以下文章