JS Implementation Viewer Mode

Source: Internet
Author: User

  Observer Pattern: The main motive behind the design of this pattern is to facilitate the formation of loose coupling. In this pattern, not one object invokes another object's method, but one object subscribes to the specific activity of another object and is notified when the state changes. Subscribers are also referred to as observers, and the objects that complement observation are called publishers or topics. When an important event occurs, the Publisher notifies (invokes) all subscribers and may often pass messages in the form of an event object.

Idea: The Publisher object requires an array-type attribute to store all subscribers. A subscription (that is, registration) is the act of adding a new subscriber to the array, and then Unregistering removes a subscriber from the array. In addition, publishing a message is looping through the list of subscribers and notifying them.

  

My general idea here is right, but a new class-as-a-subscriber is defined outside the publisher. A method getnews is defined in the Subscriber to invoke the method when the publisher publishes the message. And then the interviewer says it's too much trouble, so what if subscribers don't have this method? Then I don't quite understand ... So when the message is published directly passed the parameters: Obj.news = msg; And the interviewer says it's not more trouble? So what if the subscriber doesn't have the news property? Also have to determine whether subscribers have news this attribute, if not, there will be undifined error. Then I don't know what to do ... Then the interviewer was very nice and told me that I could use inheritance, or pass in a function at the time of registration.

After down the Internet to check the relevant, note the following:

1. Sending a message is a notification, which means invoking a method of the Subscriber object. So when a user subscribes to a message, the subscriber needs to provide one of its methods to paper's subscribe (). --------This should be the interviewer's call to pass in a method when registering.

2. The publishing object paper needs to have the following members:

A, Subscribers: an array that stores subscribers

B, subscribe (): Register/Subscribe, add subscribers to the subscribers array

C, unsubscribe (): Unsubscribe. Remove subscribers from the subscribers array

D, publish () loops through each element in the subscribers array, and invokes the method that they provide when registering

All of these three methods require a type parameter because the Publisher may trigger multiple events (such as publishing a magazine and a newspaper at the same time) and the user may choose to subscribe to only one, not the other.

  3.

First look at this article ... http://www.2cto.com/kf/201210/163500.html. I didn't see it clearly. Write the following code:

1         //because these members are common to any Publisher object, it is meaningful to implement them as part of a separate object. That way we can copy it into any object and turn any given object into a publisher. 2 3         //implement a generic publisher as follows4 5         //Define Publisher Object ... {} is to define an object6         varPublisher = {7 Subscribers: {8Any: []//Event Type:subscribers9             },TenSubscribefunction(fn,type) { OneType = Type | | ' Any '; A                 if(typeof  This. subscribers[type] = = = "undefined"){ -                      This. subscribers[type] = []; -                 } the                  This. Subscribers[type].push (FN); -             }, -Unsubscribe:function(fn,type) { -                  This. Visitsubscribers (' unsubscribe ', FN, type); +             }, -Publishfunction(publication, type) { +                  This. Visitsubscribers (' Publish ', publication,type); A             }, atVisitsubscribers:function(action,arg,type) { -                 varPubtype = Type | | ' Any, -Subscribers = This. Subscribers[pubtype], - I, -Max =subscribers.length; -                  for(i=0;i<max;i++){ in                     if(Action = = "Publish"){ - Subscribers[i] (ARG); to}Else { +                         if(Subscribers[i] = = =Arg) { -Subscribers.splice (i,1); the                         } *                     } $                 }Panax Notoginseng             } -         }; the         //defines a function, Makepublisher (), that takes an object as an object and translates it into a publisher by copying the method of the above-mentioned generic publisher into the object +         functionMakepublisher (o) { A             vari; the              for(Iinchpublisher) { +                 if(Publisher.hasownproperty (i) &&typeofPublisher[i] = = = "function"){ -O[i] =Publisher[i]; $                 } $             } -O.subscribers ={any: []}; -         } the         //Implementing paper Objects -         varPaper = {WuyiDailyfunction(){ the                  This. Publish ("Big news Today"); -             }, WuMonthlyfunction(){ -                  This. Publish ("Interesting Analysis", "monthly"); About             } $         }; -         //construct paper as a publisher - makepublisher (paper); -         //There is already a publisher. Looking at the subscription object, Joe, there are two methods of this object: A         varJoe = { +Drinkcoffee:function(paper) { theConsole.log (' Just read ' +paper); -             }, $Sundayprenap:function(monthly) { theConsole.log (' About-fall asleep reading this ' +monthly); the             } the         }; the         //Paper Register Joe (that is, Joe subscribes to paper) - Paper.subscribe (joe.drinkcoffee); inPaper.subscribe (Joe.sundayprenap, ' monthly ')); the         //that is, Joe provides a method that can be called for the default "any" event, while another method that can be called is used when an event of type "monthly" occurs. Now let's trigger some events: thePaper.daily ();//Just Readbig News Today AboutPaper.daily ();//Just Readbig News Today thePaper.monthly ();//About to fall asleep reading thisinteresting analysis thePaper.monthly ();//About to fall asleep reading thisinteresting analysis thePaper.monthly ();

JS Implementation Viewer Mode

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.