The Observer pattern defines a one-to-many relationship that allows multiple observer objects to listen to a Subject object at the same time, notifying all observer objects when the state of the object changes, enabling them to automatically update themselves.
Example: Magazine subscription
The publisher contains several methods:
varPublisher ={subscribers:function(fn,type) {type= Type | | " Any; if(typeof This. subscribers[type] = = = "undefined"){ This. subscribers[type] = []; } This. Subsribers[type].push (FN); }, Unsubscribe:function(fn,type) { This. Visitsubscribers ("Unsubscribe", Fn,type); }, Unsubscribe:function(publication,type) { This. Visitsubscribers ("Publish", Publication,type); }, Visitsubscribers:function(function, Arg,type) { varPubtype = Type | | "Any", Subscribers= This. Subscribers[pubtype], I, Max=subscribers.length; for(i=0; i<max; i++){ if(Action = = = "Publish") {Subscribers[i] (ARG); }Else{ if(Subscribers[i] = = =Arg) {Subscribers.splice (i,1); } } } }};
The following function takes an object and translates it into a publisher by copying the method of the publisher to that object:
function Makepublisher (o) { var i; for inch publisher) { if(Publisher.hasownproperty (i) &&typeof[i] = = = "function") { O[i]=publisher[i]; } } O.subscribers={any:[]};}
Paper objects, published daily and Monthly:
var paper={ daily:function() { this. Publish ("Big news Today" }, Monthly:function() { this. Publish ("Interesting Things "," monthly ");} ;
Construct the paper as a publisher:
Makepublisher (paper);
Subscriber Joe:
var joe = { drinkcoffee:function(paper) { console.log ("Just read" + paper) , sundayprenap:function(monthly) { Console.log ("About to fall Asleep to read this "+monthly);} };
Subscription:
paper.subscribe (Joe.drinkcoffee);p aper.subscribe (Joe.sundayprenap,"Monthly");
Trigger Some events:
Paper.daily ();p aper.daily ();p aper.daily ();p aper.monthly ();
Output:
This interesting things
The observer's usage scenario is that when an object changes to change other objects at the same time, and it doesn't know how many objects need to be changed, you should consider using the observer pattern.
The work of the observer pattern is decoupling, allowing both sides of the coupling to rely on abstraction, rather than relying on specifics. So that their changes will not affect the change on the other side.
JavaScript design pattern-Viewer mode