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)