Home > Web Front-end > JS Tutorial > body text

JavaScript Design Patterns Observer Pattern (Publisher-Subscriber Pattern)_javascript skills

WBOY
Release: 2016-05-16 16:35:42
Original
1083 people have browsed it

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.

Copy code The code is as follows:

div.onclick = function click (){
alert ( ”click’ )
}

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:

Copy code 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 remembered that I should add a sound function to the game. I should add a line of code to the image loader.
Copy code The code is as follows:

loadImage( imgAry, function(){
Map.init();
Gamer.init();
Sount.init();
} )

But the colleague A who wrote this module went on a trip abroad. So I called him, hello. Where is your loadImage function? Can I change it? Are there any side effects after changing it? As you can imagine, it’s all kinds of uneasy. happened. What if we could have written it like this:
Copy code 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 completed, it doesn't care what happens in the future, because its work has been completed. Next it only needs to publish a signal.

Copy code The code is as follows:

loadImage.trigger( ”ready’ );

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.

Copy code The code is as follows:

Events = function() {
var listen, log, obj, one, remove, trigger, __this;
obj = {};
__this = this;
listen = function( key, eventfn ) { //Throw your resume into the box, the key is your 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, use the observer mode to make a small adult TV application.

Copy code The code is as follows:

//Subscribers
var adultTv = Event();
adultTv .listen( ”play', function( data ){
alert ("whose movie is today" data.name );
});
//Published by
adultTv .trigger( ”play', { ‘name’: ‘Aso Nozomi’ } )
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template