javascript-Observer pattern (Publish/subscribe)

Source: Internet
Author: User
Tags emit event listener

javascript-Observer pattern (Publish/subscribe)

The observer pattern, also called the Publish-subscribe pattern, defines a one-to-many relationship that allows multiple observer objects to listen to a Subject object at the same time, notifying all observers when the subject's state changes. It is composed of two types of objects, subject and observer, the topic is responsible for publishing events, while observers subscribe to these events to observe the subject, the Publisher and Subscribers are fully decoupled, do not know each other's existence, both share only a custom event name.
In Nodejs, EventEmitter native support for this pattern was achieved. In JavaScript, the event listener mechanism can be understood as an observer pattern.

Here is a JS custom pubsub, read the following code carefully to help you understand the observer pattern. Please see GitHub for related codes.

         function PubSub() {           This. handlers = {}; } Pubsub.prototype = {//Subscribe to EventsOn function(EventType, handler){                varSelf = This;if(! (EventTypeinchSelf.handlers)) {Self.handlers[eventtype] = []; } self.handlers[eventtype].push (handler);return  This; },//Trigger event (Publish event)Emit function(eventtype){               varSelf = This;varHandlerargs =Array. Prototype.slice.call (arguments,1); for(vari =0; i < self.handlers[eventtype].length;               i++) {self.handlers[eventtype][i].apply (Self,handlerargs); }returnSelf },//Delete subscription eventsOff function(EventType, handler){                varCurrentevent = This. Handlers[eventtype];varLen =0;if(currentevent) {len = currentevent.length; for(vari = len-1; I >=0; i--) {if(Currentevent[i] = = = Handler) {Currentevent.splice (I,1); }                    }                }return  This; }        };varPubSub =NewPubSub ();varcallback = function(data){Console.log (data); };//Subscribe to event aPubsub.on (' A ', function(data){Console.log (1+ data);        }); Pubsub.on (' A ', function(data){Console.log (2+ data);        }); Pubsub.on (' A ', callback);//Trigger event aPubsub.emit (' A ',' I am the parameter ');//Delete the subscription source for event a callbackPubsub.off (' A ', callback); Pubsub.emit (' A ',' I am the parameter of the second call ');

Run the results.

javascript-Observer pattern (Publish/subscribe)

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.