JavaScript Design Patterns-observer patterns

Source: Internet
Author: User
Tags message queue

The observer pattern, also known as the publish-subscribe pattern or message mechanism, defines a dependency relationship that solves the coupling between the subject object and the Observer's function.

By using the observer pattern, we can solve the inter-module communication problem in team development, which is a feasible solution of decoupling between modules.

First, let's create the Observer object, which has a message container and three methods, namely, the method to subscribe to the message, the method to send the subscription message, and the way to unsubscribe from the message. As follows:

//Place the observer in the closure and execute immediately when the page loadsvarObserver = (function () {    //To prevent Message Queuing from being tampered with by making the message container a static private variable    var_messages = {}; return{regist:function() {},//Register MessageFire:function() {},//Publish a messageRemovefunction() {}//Cancel Message    };}) ();

Now that the observer's prototype has come out, the next thing we do is step through these three methods.

1. The role of the registration message is to push the subscriber's message into the message queue, so we need to accept two parameters: the message type and the corresponding processing action.

When pushed into Message Queuing, if this message does not exist, you should create a message type and put the message in the message queue, and if this message exists, you should push the message execution method into the corresponding execution method queue for the message, which is to ensure that multiple modules can execute successfully when registering the same message.

function (Type, fn) {    if (typeof _messages[type] = = = ' undefined ') {        // If this message does not exist, a message container is created     }    else  {        //  message exists, the action method is pushed into the action execution sequence corresponding to the message    }}

2. The ability to publish messages is that when an observer publishes a message, the messages subscribed to by all Subscribers are executed sequentially. Therefore, you should accept two parameters: the message type and the parameters to be passed when the action executes.

It is necessary to verify the existence of the message before executing the message action queue, and then traverse the message execution method queue and execute it sequentially.

function (type, args) {    if (!  _messages[type]) {        return;    };     var events = {        type:type,        | |  {}    };      for (var i = 0, len = _messages[type].length; i < Len; i++) {        _messages[type][i].call (this  , args);    

3. The ability to unregister a message removes the message from the message queue, so we can pass two parameters: the message type and the action function.

If only the message type parameter is passed, all action functions that subscribe to this message type are unregistered,

If both are passed, only the action function of the current pass parameter of this message type is unregistered.

Of course, in order to avoid the deletion of message action when the message does not exist, it is necessary to verify the existence of messages in the message queue.

function (Type, fn) {        if (!  fn) {        null;         return ;    };     if instanceof Array) {        var i = _messages[type].length-1;          for (; I >= 0; i--) {            = = = fn && _messages[type].splice (i, 1);}        ;}    }

At this point, the Observer pattern is complete! You can test it a little bit:

var function () {    console.log (1);} var function () {    Console.log (2);} Observer.regist (' test ', fn1); Observer.regist (' test ', fn2); Observer.fire (' test '); 1 2observer.remove (' test ', fn1); Observer.fire (' test '); 2

JavaScript Design Patterns-observer patterns

Related Article

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.