Observer mode for JavaScript design patterns (Publisher-subscriber mode) _javascript tips

Source: Internet
Author: User

Observer mode (also known as publisher-Subscriber mode) should be one of the most common patterns. are used in a lot of languages. Including the DOM events we normally touch. It is also an observer pattern implemented between JS and Dom.

Copy Code code as follows:

Div.onclick = function Click () {
Alert ("click")
}

Just subscribe to the div click event. When you click on the div, the function click is triggered.

So what exactly is the Observer model? Look at the Observer pattern in life first.

Hollywood has a famous saying. "Don't call me, I'll call you." This sentence explains the ins and outs of an observer pattern. where "I" is the publisher, "You" is the Subscriber.

For example, when I came to the company for an interview, every interviewer would say to me, "Please leave your contact information and we'll let you know." Here "I" is a subscriber, and the interviewer is the publisher. So I do not have to ask every day or every hour to interview results, the communication initiative is in the hands of the interviewer. And I just need to provide a way to contact.

The Observer pattern is a good way to achieve decoupling between 2 modules. If I am developing a HTML5 game in a team. When the game starts, you need to load some picture footage. After loading these pictures, the game logic begins. Suppose this is a project that requires a lot of people to work together. I finished the gamer and map module, while my colleague a wrote a picture loader loadimage.

The code for LoadImage is as follows:

Copy Code code as follows:

LoadImage (Imgary, function () {
Map.init ();
Gamer.init ();
} )

When the picture is loaded, the map is rendered and the game logic is executed. Well, this program works fine. Suddenly one day, I think of the game should be added sound function. I should get the picture loader to add a line of code.
Copy Code code as follows:

LoadImage (Imgary, function () {
Map.init ();
Gamer.init ();
Sount.init ();
} )

But colleague A, who wrote this module, went on a trip to the field. So I called him, hello. where is your loadimage function, can I change it, and then have no side effects. As you can imagine, all kinds of things that are not calm happen. What if we could have written it this way:
Copy Code code as follows:

Loadimage.listen ("Ready", function () {
Map.init ();
})
Loadimage.listen ("Ready", function () {
Gamer.init ();
})
Loadimage.listen ("Ready", function () {
Sount.init ();
})

After the LoadImage is finished, it doesn't care what will happen in the future, because its work is done. Then it just releases a signal.

Copy Code code as follows:

Loadimage.trigger ("Ready ');

Then the object that listens to the LoadImage ' ready ' event will be notified. Just like the last interview example. The interviewer doesn't care where the interviewer is going to eat after the interview results are received. He is only responsible for collecting the candidates ' resumes. When the interview results come out, follow the phone on the resume to notice.

Having said so many concepts, come to a concrete realization. The implementation process is actually very simple. The interviewer throws a resume in a box and the interviewer calls the results in a box with a resume at the right time.

Copy Code code as follows:

Events = function () {
var listen, log, obj, one, remove, trigger, __this;
obj = {};
__this = this;
Listen = function (key, EVENTFN) {//The resume throws the box, the key is the contact method.
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 inform 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 use the Observer mode to do a small application of adult TV station.

Copy Code code as follows:

Subscribed by
var Adulttv = Event ();
Adulttv. Listen ("Play", function (data) {
Alert ("Who's movie Today" + Data.name);
});
Published by
Adulttv. Trigger ("Play", {' name ': ' Hemp-Greek '})

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.