JavaScript Publish subscription PubSub mode

Source: Internet
Author: User
Tags emit

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.