Categories
Uncategorized

JavaScript Design Patterns – observer mode

The observer pattern is also known as publish – subscribe model is a design pattern in behavioral patterns;

definition:

Subject an observer pattern defines many dependencies, when the state is dependent on the object is changed, all of its dependents will get notified;

Vernacular explanation:

If you go to the Apple store to buy the latest iphone11, because iphone11 just come out soon, is at the peak season, short supply; when you go to the store, the clerk tells you temporarily out of stock, but you can leave your contact way, if the goods arrived, will inform; of course you would not have to go to the store every day to ask iphone11 arrival no, it will not call every day to the store, because you have your own work and life, it is impossible there are so many leisure time; so in this case, the clerk let you leave contact information, you notice the arrival of the first time, will not bring trouble to you, and you only need to wait for the phone to store; and this method is a typical model of the observer;

First we have to analyze:

1. Subscribe Methods: We Contact to store clerk is a kind of message subscription news, because the only way you can know iphone11 timely arrival, we all need a subscription specific methods of behavior;

2. Book list: You know iphone11 belongs to the new iphone, so you certainly will not be the only person to go to a book, so the clerk for the convenience of Statistics also need a reservation list to count all the subscribers contact information and phone book version information, so we give it here defined as an object; represents the key is the subscriber’s contact details, value represents the book Mobile version of the information;

3. Publish method: When iphone11 arrival, the store will certainly be carried out according to booking list for issuing messages ( “iphone11 arrived, everyone Come grab !!!”), so stores need a way to implement released specific release behavior;,

4. unsubscribe: all things relative, can certainly be able to subscribe to unsubscribe; while waiting iphone11 notice of arrival, you hurry to use the phone, so a direct buy a section of Huawei, so iphone11 temporarily not for you needs, because you already have a cell phone so stores iphone11 whether the arrival does not make sense to you; so you do not want to be disturbed at this time, we need to unsubscribe messages; so we need a way to unsubscribe achieve specific unsubscribe behavior;

Observer pattern scenarios:

1, DOM events

If you are a front-end developer, whether the observer pattern already know whether you read this article before, but I’m sure you’ve used the Observer pattern;

document.body.addEventListener('click', function() {
    console.log('hello world!');
});

 

The code looked familiar it? Yes, this is a listening DOM events; we subscribe to click through to the body event (click subscription equivalent to the above method), because the browser does not know what time you click the mouse, so wait when you click an event will trigger trigger function gives you an announcement (published method); DOM event is to implement an observer pattern;

2, vue way binding v-model

We as a front-end developer, know for sure vue is a framework for MVVM pattern; core vue is a two-way binding, to achieve it is actually a two-way binding observer mode; because after you first bind a data (subscription method), the browser does not know what time you modify the page you bind all the data or rely on the data node is actually a book list, so you only modify the value of the data when, vue will notice (delivery method) to the data-dependent method / or data corresponding to a refresh operation;

Of course, maybe no means limited to observer mode of implementations scene, in our lives, there are examples of business scenarios many observers mode, before we first chapter introduces design patterns factory pattern when he said, is a design pattern an idea to solve the problem, rather than a fixed formula, then how do we implement the observer pattern here?

Observer pattern implementation:

    //

Definition of business

var merchants = {}; //

Define subscription list

merchants.orderList = {}; //

The book's increase added to the reservation list (subscription method)

merchants.listen = function(id,info){ //

if it exists

if(!this.orderList[id]){ //

(Reservation list)

this.orderList[id] = []; } //

The user's predefined product information stored in the array

this.orderList[id].push(info); } //

Ads (published method)

merchants.publish = function(){ var id = Array.prototype.shift.call(arguments); var infos = this.orderList[id]; if(!infos || infos.length === 0){ console.log("您还没有预定信息"); return false; } for(var i = 0;i < infos.length;i++){ console.log("预定成功"); console.log("尊敬的用户:") infos[i].apply(this,arguments); console.log("到货了"); } } //

unsubscribe

merchants.remove = function(id,fn){ var infos = this.orderList[id]; if(!infos){ return false} if(!fn){ console.log(123); }else{ for(var i = 0;i < infos.length;i++){ if(infos[i] === fn){ infos.splice(i,1); } } } } let customeA = function(){ console.log("黑色尊享版一台"); } merchants.listen("15172103336",customeA); merchants.remove("15172103336",customeA); merchants.publish("15172103336");

The above code a little bit long, but not difficult; First, we define an object as a business, and then define an empty object as subscription lists, and then step by step to achieve our subscription methods and publishing as well as a way to unsubscribe ; logic is not complicated, but some need to explain the syntax:

var id release method = Array.prototype.shift.call (arguments); phrase means that the merchants.publish ( “15172103336”); when the method call is returned to the first argument and then copy it to id, so in fact, at this time id value of “15172103336”;

infos [i] .apply (this, arguments); this method is not particularly easy to understand, first of all infos are filled with the subscriber’s phone number and the phone version information, so we infos [i] .apply (this, arguments); this method is actually a “15172103336” corresponds to the phone version information function is called again; in fact equal infos [i] (arguments);

 

The observer pattern, whether in the field or front-end application in real life are all very common scenario, have to learn the observer mode using the knowledge we learn vue source code, of course, not limited to this, so we should learn observer mode, saying: “! your product, you fine chemicals” today efforts, there will always be replaced in the future to return your wages! Ha ha ha

 

Leave a Reply