First, using the array cache Subscriber subscription message, when the Subscriber subscribes to the message, push the subscription message to the queue of the specified message, and when the publisher publishes the message, we traverse the execution push to the specified message queue for the callback event.
varPubsub= (function(){ vareventobj={}; return{subscribe:function(EVENT,FN) {eventobj[event]=fn}, publish:function(event) {if(Eventobj[event]) eventobj[event] (); }, off:function(EVENT,FN) {if(Eventobj[event]) eventobj[event]=NULL; }}) () Pubsub.subscribe (' Event ',function() {Console.log ("Executing, but only one action can be bound to an event");}) Pubsub.publish ("Event");
//supports one event bound multiple operationsvarPubsub1= (function(){ varquence={};//{' type1 ': [], ' type2 ': []} return{subscribe:function(EVENT,FN) {if(!quence[event]) quence[event]=[]; Quence[event].push (FN); }, Publish:function(event) {varEventquence=Quence[event], Len=eventquence.length; if(len>0) {Eventquence.foreach (Item,index)={item ()})} }, off:function(EVENT,FN) {varEventquence =Quence[event]; if(eventquence) {quence[event]= Eventquence.filter (function(item) {returnItem!==fn; }); } } }})()functionFirst () {Console.log ("Emit first")}functionsecond () {Console.log ("Emit second")}pubsub1.subscribe (A, first) Pubsub1.subscribe (A, second) Pubsub1.off (' A ', first)//unsubscribe from a first eventPubsub1.publish ("a");
JavaScript Publish subscription PubSub mode