Learning JavaScript design patterns: Observer Pattern _ javascript skills

Source: Internet
Author: User
This article mainly introduces the observer mode in the JavaScript design mode. If you are interested in the JavaScript design mode, refer to it. I. Definition

Observer mode (publish-subscribe mode): it defines a one-to-many dependency between objects. When the status of an object changes, all objects dependent on it will be notified.
In JavaScript, the event model is generally used to replace the traditional observer mode.
Benefits:

  • (1) it can be widely used in asynchronous programming and is an alternative to passing callback functions.
  • (2) It can replace the hard-coded notification mechanism between objects. An object does not need to be displayed to call an interface of another object. The two objects can be easily decoupled.

Ii. DOM Event-Observer mode example

You need to monitor the user's clicking document. body action, but we cannot predict when the user will click.
Therefore, we subscribe to the click Event on document. body. When the body node is clicked, the body node will publish this message to the subscriber!

Document. body. addEventListener ("click", function () {console. log (1) ;}, false); // multiple subscriber documents are allowed. body. addEventListener ("click", function () {console. log (2) ;}, false); doucment. body. click ();

A website has header, nav navigation, message list, and other modules. Rendering of these modules requires obtaining user login information.
(1) General statement:

$. Ajax ({url :'. /login ', type: 'post', contentType: 'application/json', dataType: 'json', success: function (data) {if (data. status = "success") {// login successful, rendering header, nav header. setInfo (data. headerInfo); nav. setInfo (data. navInfo );}}});

(2) Use the observer mode to easily decouple!

$. Ajax ({..., success: function (data) {if (data. status = "success") {// login is successfully published. trigger ("loginsuccess", data) ;}}); var header = (function () {// listen to the 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 Mode

/** 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, f Ind, 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 _ 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] = [] ;}}; // release _ trigger = function () {var cache = _ shift. call (arguments), key = _ shift. call (arguments), args = arguments, _ self = this, ret, stack = Cache [key]; if (! Stack |! Stack. length) {return;} return each (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) {ret Urn 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 ;})();

I hope 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.