The observer pattern (also called the publisher-subscriber pattern) should be one of the most commonly used patterns. It is widely used in many languages. Including the dom events we usually come into contact with. It is also implemented between js and dom An observer pattern.
As long as you subscribe to the click event of the div. When the div is clicked, the function click will be triggered.
So what is the observer pattern? Let’s first look at the observer pattern in life.
There is a famous saying in Hollywood. "Don't call me, I will call you." This sentence explains the ins and outs of the observer pattern. Where "I" is the publisher and "you" is the subscriber.
For another example, when I came to the company for an interview, every interviewer would say to me after the interview: "Please leave your contact information and we will notify you if there is any news." Here "I" is the subscriber and the interviewer is the publisher. So I don’t have to ask about the interview results every day or every hour. The initiative of communication rests with the interviewer. And I just need to provide a contact information.
The observer pattern can well achieve decoupling between two modules. Suppose I am developing an HTML5 game in a team. When the game starts, some image materials need to be loaded. After loading these images, the game logic is executed. Assume this is a project that requires multi-person cooperation. I completed the Gamer and Map modules, and my colleague A wrote an image loader loadImage.
The code for loadImage is as follows:
After loadImage is completed, it doesn't care what happens in the future, because its work has been completed. Next it only needs to publish a signal.
Then objects that listen to the 'ready' event of loadImage will be notified. Just like the last interview example. The interviewer does not care at all where the interviewers will go to eat after receiving the interview results. He is only responsible for conducting the interview. Collect the resumes of the candidates together. When the interview results come out, you will be notified one by one according to the phone number on the resume.
After talking about so many concepts, let’s give a concrete implementation. The implementation process is actually very simple. The interviewer throws the resume into a box, and then the interviewer takes the resume in the box and calls one by one at the right time to inform them of the result.
Finally, use the observer mode to make a small adult TV application.