JavaScript design pattern-Observer pattern (study notes)

Source: Internet
Author: User

JavaScript design pattern-Observer pattern (study notes)
The importance of Design Pattern is self-evident for software development. code reusability, maintenance, and scalability have always been the pursuit of software engineering! It seems difficult for me to understand the design pattern for javascript, and it may not even be used for FE, which only performs graph cutting and a small amount of interaction, however, when you start to use Angular/Backbone and other frameworks, you will not be able to avoid design patterns, MVC/MVVM, and other things (I am a headache ). When I first started programming for about three months, I read a book titled big talk design patterns, which was written in C #. I am speechless, it seems that a strong programming language is difficult for me to write a weak type, so I learned C # basic syntax rules... At the beginning of this year, I learned the basic syntax rules of JAVA... However, my original intention has been abandoned and fallen to a thick gray layer. For self-taught programming, I don't know the order of learning programming seems to suffer a lot, but there is always a beginning! The above can be skipped. First, let's take a look at my personal understanding of the "Observer mode": The Observer mode is also called the "Publish/Subscribe mode ", publishing and subscription are obviously the functions of two different objects, such as RSS. Zhihu is a publisher (who publishes high-approval answers to some questions). As a subscriber, I subscribe to zhihu's published content in my mailbox ), my colleagues and my boss subscribe to zhihu, so in this model, there is a publisher with three subscribers. In specific programming, if a publisher has new content and needs to push data to the subscriber, the new content (state) and subscriber (observers) are what the publisher needs to include, if you subscribe to or unsubscribe, you must update the subscriber list in the publisher. The following is an explanation of the publisher's 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. splice (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, you can use filter, forEach, and other new features of the array class for processing. The third notice function indicates that the publisher has something new and notifies everyone in the subscriber list that they have new content (state). You can update your mailbox. The content is transmitted to the update function of each subscriber. What about subscribers? The subscriber is very simple. You only need to have an update function (each subscriber may have a different update function. For example, if I put it in my mailbox, my colleagues will use the subscription function, by the way, I deleted the old one, and my boss forwarded the data to Gmail ). The following is the code for interpreting subscriber information:
// Subscribe function Subscribe () {this. update = function (data) {console. log (data );};}

 

In fact, every subscriber has this update, so we should usually add it to the prototype of the constructor. When the default update function does not meet the requirements, you can set an independent update for each subscriber's instance, for example, sending this data to someone else. Finally, let's look at how to apply it.
// 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 have manually set the content (state) of the publisher at the end and asked the publisher to send a notice ). In a real project, the publisher's content may be obtained from the background or input from somewhere on the foreground. However, is it unnecessary for the publisher to manually call the notification after each update? Now that the content has been updated, you must notify others. Then we can bind the content update and notification, and check the following code:
<! DOCTYPE html> 

 

For the above content, it may not be related to the actual problems in our project, so we can substitute this design pattern for an example: Three text boxes ABC, where A can be edited, B and C cannot be edited, and the value of B is the value of A plus the suffix "@ w3c.com". The value of C is the value of A with the prefix "ID -".
<! DOCTYPE html> 

 

In the book "big talk Design Patterns", I mentioned a similar situation: What if the subscriber wants to do something different for the publisher's content? For example, when a button and three rectangles are clicked, the first rectangle increases the width, the second rectangle increases the height, and the third rectangle changes to a rounded rectangle. How can this problem be solved? Of course, we can write the specific implementation code in the update of the three rectangles, but isn't the update function described? In this book, "event Delegate" is used to solve this problem (here event Delegate and event Delegate in DOM are two different things ), I personally understand that this "event Delegate" can be represented in an array in javascript, and then updated by different subscriber names are put in it, and then called one by one. In the book javascript design patterns, the implementation of observer patterns also adopts the "push" method. The chapter finally asks how to implement the "pull" method? I personally understand that when a publisher pushes data, it is mandatory to urge the subscriber to update the data. However, in the PULL mode, the publisher only contains the latest content, no notification (notice) No subscriber list. When a subscriber needs to obtain data, it can pass in the Publisher Object in its corresponding update method. For more information about this model, see this article. O (partition _ partition) o

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.