This article mainly introduces the observer mode (publisher-subscriber mode) in JavaScript design mode. This article describes the observer mode in JavaScript in detail, you can refer to the observer mode (also known as publisher-subscriber mode) as one of the most common modes. it is widely used in many languages. including dom events that we normally access. it is also an observer mode implemented between js and dom.
The Code is as follows:
P. onclick = function click (){
Alert ("click ')
}
You only need to subscribe to the click event of p. When you click p, function click is triggered.
So what is the observer pattern? First, let's look at the Observer Pattern in life.
There is a famous saying in Hollywood: "Don't call me, I'll call you." This explains the ins and outs of the observer model. "I" is the publisher and "you" is the subscriber.
For another example, when I come to the company for an interview, Every interviewer will say to me after the interview: "Please leave your contact information. We will notify you of any news ". Here "I" is the subscriber and the interviewer is the publisher. Therefore, I don't have to ask about the interview results every day or every hour. The initiative of communication lies in the hands of the interviewer. I only need to provide a contact information.
The observer mode can be used to decouple two modules. Assume that I am developing an html5 game in a team. When the game starts, I need to load some picture materials. After these images are loaded, the game logic is started. suppose this is a project that requires collaboration among multiple people. I completed the Gamer and Map modules, and my colleague A wrote an image loader loadImage.
The loadImage code is as follows:
The Code is as follows:
LoadImage (imgAry, function (){
Map. init ();
Gamer. init ();
})
After the image is loaded, the map is rendered and the game logic is executed. well, this program runs well. suddenly one day, I thought I should add the sound function to the game. I should add a line of code to the image loader.
The Code is as follows:
LoadImage (imgAry, function (){
Map. init ();
Gamer. init ();
Sount. init ();
})
However, colleague A wrote this module and traveled to other places. so I called him. Hello. where is your loadImage function? Can I change it? Is there any side effect after it is changed. as you might think, all sorts of unconfirmed things have happened. if we can write it like this:
The Code is as follows:
LoadImage. listen ("ready ', function (){
Map. init ();
})
LoadImage. listen ("ready ', function (){
Gamer. init ();
})
LoadImage. listen ("ready ', function (){
Sount. init ();
})
After loadImage is complete, it does not care about what will happen in the future, because its work has been completed. Next, it only needs to publish a signal.
The Code is as follows:
LoadImage. trigger ("ready ');
The objects listening to The 'ready' event of loadImage will receive notifications. just like the previous interview example. the interviewer does not care where the interviewer will go for dinner after receiving the interview results. he is only responsible for collecting the interviewer's resume. when the interview results come out, follow the phone number on your resume to notify you one by one.
After talking about so many concepts, let's take a specific implementation. The implementation process is actually very simple. The interviewer threw his resume into a box, and then the interviewer made a phone call to inform the result at the right time.
The Code is as follows:
Events = function (){
Var listen, log, obj, one, remove, trigger, _ this;
Obj = {};
_ This = this;
Listen = function (key, eventfn) {// you can leave your resume in a box. The key is the contact information.
Var stack, _ ref; // stack is a box
Stack = (_ ref = obj [key])! = Null? _ Ref: obj [key] = [];
Return stack. push (eventfn );
};
One = function (key, eventfn ){
Remove (key );
Return listen (key, eventfn );
};
Remove = function (key ){
Var _ ref;
Return (_ ref = obj [key])! = Null? _ Ref. length = 0: void 0;
};
Trigger = function () {// The interviewer calls to notify the interviewer
Var fn, stack, _ I, _ len, _ ref, key;
Key = Array. prototype. shift. call (arguments );
Stack = (_ ref = obj [key])! = Null? _ Ref: obj [key] = [];
For (_ I = 0, _ len = stack. length; _ I <_ len; _ I ++ ){
Fn = stack [_ I];
If (fn. apply (_ this, arguments) === false ){
Return false;
}
}
Return {
Listen: listen,
One: one,
Remove: remove,
Trigger: trigger
}
}
Finally, we use the observer model to make a small application of adult TV stations.
The Code is as follows:
// Subscriber
Var adultTv = Event ();
AdultTv. listen ("play", function (data ){
Alert ("who is the movie today" + data. name );
});
// Publisher
AdultTv. trigger ("play", {'name': 'mastoch '})