JavaScript observer mode (Classic) _ javascript skills

Source: Internet
Author: User
The Observer mode is also called the Observer mode. It is one of 23 software design modes proposed by GoF. The Observer mode is one of the behavior modes. Its function is to automatically notify other associated objects when the status of an object changes. The Observer mode is also called the Observer mode, it is one of 23 software design modes proposed by GoF. The Observer mode is one of the behavior modes. It is used to automatically notify other associated objects and refresh the object status when the status of an object changes.

Concept of Observer Mode

The Observer mode is one of the behavior modes. It is used to automatically notify other associated objects and refresh the object status when the status of an object changes.
The Observer mode provides a synchronous communication method for associated objects to ensure the State synchronization between an object and other objects dependent on it.

Role in Observer mode:

Subject (observer)
The object to be observed. When the state to be observed changes, all observer objects in the queue need to be notified. Subject needs to maintain (add, delete, and notify) the queue list of an observer object.
ConcreteSubject
The specific implementation of the observer. Includes some basic attribute statuses and other operations.
Observer (Observer)
Interface or abstract class. When the status of the Subject changes, the Observer object will be notified through a callback function.
ConcreteObserver
The specific implementation of the observer. Some specific business logic processing will be completed after the notification is received.

The observer mode (also known as the publisher-subscriber mode) is 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.

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:

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.

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:

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.

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.

Events = function () {var listen, log, obj, one, remove, trigger, _ this; obj ={}__ this = this; listen = function (key, eventfn) {// put the resume in a box, and 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 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.

// Subscriber var adultTv = Event (); adultTv. listen ("play", function (data) {alert ("who is the movie today" + data. name) ;}); // publisher adultTv. trigger ("play", {'name': 'mastoch '})

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.