JavaScript Design Patterns

Source: Internet
Author: User

Design pattern for software development, its importance is self-evident, code can be reused, maintainable, extensible has always been the pursuit of software engineering! For a person who learns JavaScript, it may seem difficult to understand the design pattern, and it might not even be possible to use an FE that only transduction, with little interaction, but when you start using frameworks like Angular/backbone, you can't avoid design patterns, mvc/ MVVM these things up (I'm a headache anyway).

I learn the design pattern is just beginning to contact programming about three months, read a book, "Big Talk design mode", in the C # language to write, I am very silent, because the strong type of programming language for me this kind of writing weak type of hair boy, seems to have difficulties ah, so I learn C # basic grammar rules to ... Early this year I learned the basic rules of Java Grammar ... However, my original intention has been abandoned in the side, fell on a thick layer of gray. For self-taught programming, I do not know that the sequence of learning programming seems to suffer a lot, but always have the beginning!

The above can be skipped directly

First of all, I have a personal understanding of the Observer pattern: The Observer pattern, also known as the Publish-subscribe (publish/subscribe) mode, is clearly a function of two different objects, such as RSS. It is a publisher (post some high-level answers to some questions), I am a subscriber (I subscribe to the relevant post in my mailbox), my colleagues and my boss have subscribed to it, so in this model there is a publisher with three subscribers.

In the specific programming, the publisher has the new content, needs to push the data to the Subscriber, then the new content (state), the Subscriber (observers) is what the publisher needs to include, who subscribes, who has unsubscribed, then wants to update the Subscriber list in the publisher. The following is an explanation of the publisher's relevant information code:

Publisher function Publisher () {this.observers = [];        This.state = "";            } publisher.prototype.addob=function (Observer) {var flag = false;                    for (var i = this.observers.length-1; I >= 0; i--) {if (this.observers[i]===observer) {                                Flag=true;            }            };            if (!flag) {THIS.OBSERVERS.PUSH (Observer);        } return this;            } publisher.prototype.removeob=function (Observer) {var observers = This.observers; for (var i = 0; i < observers.length; i++) {if (observers[i]===observer) {OBSERVERS.S                Plice (i,1);            }            };        return this;            } publisher.prototype.notice=function () {var observers = This.observers; for (var i = 0; i < observers.length; i++) {observers[i].update (this.state);        }; }

When traversing the observers array, the above can be handled using the new features of the array class filter, foreach, and so on. The third notice function means that the publisher has something new and then notifies everyone in the Subscriber list that I have the new content (state) and you have to update your email. Here, the content is passed to each subscriber's update function.

So what about subscribers? Subscribers are very simple, only need to have an update function (each Subscriber update may not be the same, for example, I put in the mailbox, my colleagues will subscribe to the pick up, and by the way the old deleted, my boss to the data forwarded to Gmail). The following is an explanation of the subscriber-related information code:

Subscriber        function Subscribe () {            this.update = function (data) {                  console.log (data)            };        }

In fact, because each subscriber has this update, we should usually add it to the constructor's prototype, and when this default update function does not meet the requirements, you can set up a separate update for each Subscriber instance, such as sending this data to someone else. Finally let's see how to apply.

The actual application        of var oba = new Subscribe (),            obb = new Subscribe ();        var PBA = new Publisher ();        Pba.addob (OBA);        Pba.addob (OBB);        Oba.update = function (state) {            console.log (state+ "hello!");        }        Obb.update = function (state) {            console.log (state+ "world!");        }        Pba.state = "open";        Pba.notice ();

As you can see, we finally set up its content (state) on the publisher manually and asked him to send a notification (notice). In a real-world project, the publisher's content might be obtained from the background or entered from somewhere in the foreground. But is it a bit superfluous for publishers to manually invoke notifications each time they update their content? Now that we have updated the content, we must inform others. Then we'll bind the content update with the notification, and look at the following code:

<! DOCTYPE html>

The above may not be related to the actual problems in our project, then we will take this design pattern, do an example: three text box ABC, where A is editable, B and C is not editable and B is the value of a is a value plus the suffix "@w3c. com", the value of C is the value of a plus prefix " Id-".

<! DOCTYPE html>

In "Big talk design mode," a similar scenario is mentioned: if the Subscriber is doing something different for the publisher's content? For example, a button and three rectangles, when the button is clicked, the first rectangle increases the width, the second rectangle increases the height, and the third rectangle becomes a rounded rectangle. Of course we can write the specific implementation code in the three rectangle update, but does this update not have a specific function description? The book solves this problem with "event delegation" (where event delegates and event delegates in the DOM should be different), and I personally understand that this "event delegate" can be represented in JavaScript using an array, followed by an update of each subscriber's name, and then called.

In the JavaScript design model, the implementation of the observer pattern is also a "push" approach, the chapter's final rhetorical question to how to achieve "pull" this way?

I personally understand: when the publisher pushes the data is mandatory, prompting subscribers to update (update), but in the "pull" mode, the publisher itself only contains the latest content, no notification (notice) No Subscribers list, When a subscriber needs to get the data, the Publisher object is passed into its corresponding Update method. Small white See, please have different understanding of the mode of the Tao friends more correct. O (∩_∩) o

Category: JavaScript

JavaScript Design Patterns

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.