The observer pattern for JavaScript design patterns

Source: Internet
Author: User
Tags array log new features return

Design patterns for software development of the importance of self-evident, code reusable, maintainable, scalable is always the pursuit of software engineering! For me, a javascript person, it seems difficult to understand design patterns, and it may not even be used for Chettu only, with a small amount of interaction, but when you start using frames like angular/backbone, you can't avoid design patterns, mvc/ MVVM These things (I'm a headache anyway).

I learned that design patterns are just starting to touch programming for about three months, read a book "Dahua design Mode", which is written in C # language, I am very silent, because the strong type of programming language for my writing weak type of hair head kid, seems to have difficulties ah, so I learned C # basic grammar rules go ... Earlier this year I learned the basic grammar rules of Java ... However, my original intention has been abandoned in the side, fell on a thick layer of gray. For self-study programming, I do not know the sequence of learning programming seems to suffer a lot, but always have to start!

The above can skip directly

Let's start with my personal understanding of the Observer model: The Observer pattern is also known as the "Publish-subscribe (publish/subscribe) mode", and the publication and subscription are clearly features of two different objects, such as RSS. Knowing is a publisher (posting some high approval answers to some questions), as a subscriber (I subscribe to the relevant posted content in my mailbox), my colleagues and my boss subscribe to know, so in this model, there is a publisher with three subscribers.

In specific programming, the publisher has a new content, to push data to subscribers, the new content (state), what the Subscriber has (observers) is what the publisher needs to include, who subscribes, and who unsubscribe, updates the list of subscribers in the Publisher. The following is an explanation of the relevant information code for the Publisher:


Published by
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 the new features of the array class, filter, foreach, and so on. The third notice function indicates that the publisher has something new, and then notifies everyone in the Subscriber list that I have new content (state) and you take it to update your email. The content is passed to the update function for each subscriber.

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


Subscribed by
function Subscribe () {
This.update = function (data) {
Console.log (data);
};
}



In fact, because every subscriber has this update, we should usually add it to the builder's prototype, and when this default update feature is not satisfied, 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 it.


Practical application
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 up its content (state) at the end and asked him to give notice (notice). In a real-world project, the publisher's content may be acquired 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 you have updated the content, you must inform others. So we're going to bind the update of the content to the notification, and look at the following code:


<! DOCTYPE html>
<meta charset= "UTF-8" >
<title>Document</title>
<body>
<script type= "Text/javascript" >
Published by
function Publisher () {
This.observers = [];
var state = ""; Let this content not be directly accessible

Two new operations for State get/update
This.getstate=function () {
return state;
}
This.setstate=function (value) {
state = value;
This.notice ();
}

}
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.getstate ()); Get the content of the publisher
};
}


Subscribed by
function Subscribe () {
This.update = function (data) {
Console.log (data);
};
}

Practical application
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.setstate ("open"); The publisher updated the content
</script>
</body>



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


<! DOCTYPE html>
<meta charset= "UTF-8" >
<title>Document</title>
<body>
<div>
<label> User name: <input type= "text" id= "PBA" placeholder= "Please enter user name"/></label><br/><br
<label> Generate mailboxes: <input type= "text" id= "OBA" ReadOnly/></label>
<label> Generate Id:<input type= "text" id= "OBB" ReadOnly/></label>
</div>

<script type= "Text/javascript" >
Published by
function Publisher (obj) {
This.observers = [];
var state = Obj.value; Let this content not be directly accessible

Two new operations for State get/update
This.getstate=function () {
return state;
}
This.setstate=function (value) {
state = value;
This.notice ();
}
This.obj = obj;

}
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.getstate ());
};
}

Subscribed by
function Subscribe (obj) {
This.obj = obj;
This.update = function (data) {
This.obj.value = data;
};
}

Practical application
var oba = new Subscribe (Document.queryselector ("#oba")),
Obb = new Subscribe (Document.queryselector ("#obb"));

var PBA = new Publisher (Document.queryselector ("#pba"));

Pba.addob (OBA);
Pba.addob (OBB);

Oba.update = function (state) {
This.obj.value = state+ "@w3c. com";
}
Obb.update = function (state) {
This.obj.value = "id-" +state;
}

Pba.obj.addEventListener (' KeyUp ', function () {
Pba.setstate (This.value);
});

</script>
</body>



In the book "Big Talk Design pattern", a similar scenario is mentioned: What if the Subscriber does something different for the publisher? Like 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 turns into a rounded rectangle. Of course we can write specific implementation code within three rectangles of update, but is this update not a specific feature description? The book uses "event delegates" to solve this problem (where event delegates and event delegates in the DOM should be different), and I personally understand that this "event delegate" can be represented in a single array in JavaScript, and then put the various subscribers ' names in an update and call them all.

In the JavaScript design pattern, the implementation of the observer pattern is also in the form of "push", the final question of the chapter is how to achieve "pull" this way?

I personally understand that publishers push data in a mandatory way, prompting subscribers to update (update), but in the "pull" mode, the publisher itself contains only the latest content, no notification (notice) without a subscriber list, When the subscriber needs to get the data, it passes through the Publisher object in its corresponding Update method. Small white See, please the model has different understanding of the friends a lot of corrections.



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.