The Observer pattern is also known as the Publish/subscribe mode Publish/subscribe
It is a one-to-many relationship that allows multiple observer objects to listen to a Subject object at the same time, which notifies all observer objects when their state changes, enabling them to automatically update themselves.
1 functionMsgbus () {2 3 varMsgmap = {};//Internal message bus4 varInstance = {};5 6 7 /**8 * @function Subscribe9 * @description Subscribe message listener.Ten * @param msgtype {string}-message type to be listen. One * @param handler {function}-handler function when the message sent. A * @instance - */ -Instance.subscribe =function(msgtype,handler) { the if(Msgtype = =NULL){ -Console.error ("Message type is null"); - returninstance; - } + if(Handler = =NULL){ -Console.error ("Handler is null"); + returninstance; A } at varSubscribearray =Msgmap[msgtype]; - if(Subscribearray = =NULL){ -Subscribearray =NewArray (); -Msgmap[msgtype] =Subscribearray; - } - if(Subscribearray.indexof (handler) < 0){ in Subscribearray.push (handler); - } to returninstance; + } - the /** * * @function Unsubscribe $ * @description Unsubscribe message listener.Panax Notoginseng * @param msgtype {string}-message type to be unsubscribe. - * @param handler {function}-handler function to is removed. the * @instance + */ A theInstance.unsubscribe =function(msgtype,handler) { + varSubscribearray =Msgmap[msgtype]; - if(Subscribearray! =NULL){ $ varindex =Subscribearray.indexof (handler); $ if(Index > 0){ -Subscribearray.splice (index,1); - } the } - Wuyi returninstance; the } - Wu - /** About * @function Publish $ * @description publish message. - * @param msgtype {string}-message type to be published. - * @param data {Object}-message data. - * @instance A */ +Instance.publish =function(msgtype,data) { the varSubscribearray =Msgmap[msgtype]; - if(Subscribearray = =NULL){ $ return; the } the for(vari=0;i<subscribearray.length;i++){ the Try{ the Subscribearray[i] (data); -}Catch(e) { inConsole.error ("error when sending Message:" +msgtype); the } the } About the returninstance; the } the + returninstance; -}
Test it:
var instance = Msgbus (); Instance.subscribe ("subscribe",function(data) {Console.log (" "+ Data"}); Instance.publish (// This is cangjingkong
The observer pattern for JavaScript design patterns