The Observer pattern _javascript techniques for learning JavaScript design Patterns

Source: Internet
Author: User

I. Definition

Observer mode (publish-subscribe mode): It defines a one-to-many dependency between objects, and when an object's state changes, all objects that depend on it are notified.
In JavaScript, the event model is generally used to replace the traditional observer pattern.
Benefits:

    • (1) can be widely used in asynchronous programming, is an alternative to transfer callback function scheme.
    • (2) can replace the hard-coded notification mechanism between objects, and an object does not need to be shown to invoke an interface of another object. Two objects are easily decoupled.

II. DOM Event-Observer model example

You need to monitor user clicks on document.body, but we have no way of predicting when users will click.
So, we subscribe to the Click event on the Document.body, when the body node is clicked, the Body node will release the message to the Subscriber!

Document.body.addEventListener ("click", Function () {
  console.log (1);
}, False);

Multiple subscribers can be
document.body.addEventListener ("click", Function () {
  console.log (2);
}, False);

Doucment.body.click ();

A website has header head, nav navigation, message list and other modules. The rendering of these modules requires access to user login information.
(1) General wording:

$.ajax ({
  URL: './login ',
  type: ' Post ',
  contentType: ' Application/json ',
  dataType: ' JSON '
  , Success:function (data) {
    if (Data.status = = "Success") {
      //login succeeded, render header, Nav
      header.setinfo ( Data.headerinfo);
      Nav.setinfo (Data.navinfo);
    }
  }
);

(2) Use observer mode, very easy to decouple!

$.ajax ({
  ...,
  success:function (data) {
    if (Data.status = = "Success") {
      //Login successful, Post login success Message
      Login.trigger ("loginsuccess", data);
    }
  }
);

var Header = (function () {
  //Listener message
  login.listen ("Loginsuccess", function (data) {
    Header.setinfo ( data.headerinfo);
  };
  return {
    setinfo:function (data) {
      Console.log ("Set header information");
    }
  }
();

var nav = (function () {
  Login.listen ("Loginsuccess", function (data) {
    nav.setinfo (data.navinfo);
  });
  return {
    setinfo:function (data) {
      console.log ("Set NAV Information");}}
) ();

III. General Observer Model

* * Example: * event.create ("Namespace1"). Listen (' click ', Function (a) {* Console.log (a);
 * });
 * Event.create ("Namespace1"). Trigger ("click", 1);

  * * var Event = (function () {var global = this, Event, _default = ' default '; Event = function () {var _listen, _trigger, _remove, _slice = Array.prototype.slice, _shift =
      Array.prototype.shift, _unshift = Array.prototype.unshift, Namespacecache = [], _create, find,
        each = function (ary, FN) {var ret;
          for (var i = 0, L = ary.length i < l; i++) {var n = ary[i];
        ret = Fn.call (n, I, n);
      return ret;
    };
      Subscribe to _listen = function (key, FN, cache) {if (!cache[key]) {Cache[key] = [];
    } cache[key].push (FN);
    }; Remove Subscription _remove = function (key, cache, fn) {if (Cache[key]) {if (FN) {for (var i = Cache[key]. Length I >=0; i++) {if (cache[Key]
            [i] = = = fn) {Cache[key].splice (I, 1);
        }}}else {Cache[key] = [];
    }
      }
    }; Publish _trigger = function () {var cache = _shift.call (arguments), key = _shift.call (arguments), arg
      s = arguments, _self = This, ret, stack = Cache[key];
      if (!stack | |!stack.length) {return;
      Return all (Stack, function () {return this.apply (_self, args);
    });
    };
      Create namespace _create = function (namespace) {var namespace = namespace | | _default;
            var cache = {}, offlinestack = [],//offline event ret = {listen:function (key, FN, last) {
            _listen (Key, FN, cache);
            if (Offlinestack = = null) {return;
            } if (last = = ' last ') {offlinestack.length && Offlinestack.pop () (); } else {each (Offlinestack, function () {this ();
            });
          } offlinestack = null;
            }, One:function (Key, FN, last) {_remove (key, cache);
          This.listen (Key, FN, last);
          }, Remove:function (Key, FN, last) {_remove (key, Cache, FN);
            }, Trigger:function () {var fn, args, _self = this;
            _unshift.call (arguments, cache);
            args = arguments;
            fn = function () {return _trigger.apply (_self, args);
            };
            if (offlinestack) {return Offlinestack.push (FN);
          } return fn;

        }
        }; Return namespace?
      (Namespacecache[namespace]? Namespacecache[namespace]: namespacecache[namespace] = ret): ret;

    };
        Return {create: _create, one:function (Key, FN, last) {var event = this.create (); Event.one (Key, FN, last);
        }, Remove:function (Key, FN) {var event = this.create ();
      Event.remove (key, FN);
        }, Listen:function (Key, FN, last) {var event = this.create ();
      Event.listen (Key, FN, last);
        }, Trigger:function () {var event = this.create ();
      Event.trigger.apply (this, arguments);
  }
    };
  }();
return Event;
 })();

Hopefully this article will help you learn about JavaScript programming.

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.