JS Implementation Viewer Mode

Source: Internet
Author: User

Introduction to Basic concepts

The Observer (Observer) pattern is widely used in client-side JavaScript programming. All browser events are examples of this pattern. Another name for it is also known as custom events (custom events), which represent events that are implemented by you programmatically compared to events triggered by the browser. In addition, another alias for the pattern is also known as the subscription/release (subscriber/publisher) mode.

The main motive behind the design of this model 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.

Example: Magazine subscription

Suppose there is a publisher, paper, who publishes daily newspapers and monthly magazines. Subscribers Joe will be notified of any news that has occurred at any time.

The paper object requires a subscribers (topics) property, which is an array that stores all subscribers. The subscription behavior simply adds it to the array. When an event occurs, paper loops through the list of subscribers and notifies them. A notification means a method that invokes a Subscriber object. So when a user subscribes to a message, the subscriber needs to provide one of its methods to paper's subscribe ().

Paper also provides the unsubscribe () method, which represents removing subscribers from the Subscriber array (that is, the Subscribers attribute). Paper the last important method is publish (), which invokes the methods of these subscribers, in summary, the Publisher object paper needs to have these members:

1.subscribers an array of 2.subscribe () adds subscribers to the Subscribers Array 3.unsubscribe () removes subscribers from the Subscribers Array 4.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 topic 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.

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.

JS in the implementation of the observer pattern is implemented through callbacks, we will first define a PubSub object, which contains 3 methods: Subscribe, unsubscribe, publish.

varPubSub = {};(function(q) {varTopics = {},//array to which the callback function is storedSubuid =-1; //Publish MethodQ.publish =function(topic, args) {if(!Topics[topic]) {            return false; } setTimeout (function () {            varSubscribers =Topics[topic], Len= subscribers? subscribers.length:0;  while(len--) {subscribers[len].func (topic, args); }        }, 0); return true;    }; //Subscription MethodQ.subscribe =function(topic, func) {if(!Topics[topic]) {Topics[topic]= []; }        varToken = (+ +subuid). toString ();        Topics[topic].push ({token:token, func:func}); returntoken;    }; //Unsubscribe MethodQ.unsubscribe =function(token) { for(varMinchtopics) {            if(Topics[m]) { for(vari = 0, j = topics[m].length; I < J; i++) {                    if(Topics[m][i].token = = =token) {Topics[m].splice (i,1); returntoken; }                }            }        }        return false; };} (PubSub));

Use the following methods:

// , subscribe to a function (topics, data) {    + ":" + data);}); //  Announcement Pubsub.publish (' example1 ', ' Hello world! ' ;p ubsub.publish (' example1 ', [' Test ', ' a ', ' B ', ' C '));p ubsub.publish (' example1 ', [{' Color ': ' Blue ') }, {' text ': ' Hello '}]);

Try multiple subscribers to subscribe to the same topic:

// , subscribe to a function (topics, data) {    + ":" + data);}); // , and then subscribe to a function (topics, data) {    + "*******" + data);}); // Release Notice pubsub.publish (' example1 ', ' Hello world! ');

Output:

example1***** Hello world! Example1:helloWorld!

Reference: http://www.2cto.com/kf/201210/163500.html

Http://www.cnblogs.com/TomXu/archive/2012/03/02/2355128.html

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.