Home > Web Front-end > JS Tutorial > JavaScript Observer Pattern (Classic)_javascript tips

JavaScript Observer Pattern (Classic)_javascript tips

WBOY
Release: 2016-05-16 15:26:39
Original
1087 people have browsed it

The Observer pattern, also called the Observer pattern, is one of the 23 software design patterns proposed by GoF. The Observer pattern is one of the behavioral patterns. Its function is that when the state of an object changes, it can automatically notify other associated objects and automatically refresh the object state.

Concept of Observer pattern

Observer mode is one of the behavioral modes. Its function is to automatically notify other associated objects and automatically refresh the object state when the state of an object changes.
The Observer pattern provides a means of synchronous communication for associated objects to maintain state synchronization between an object and other objects that depend on it.

Observer mode role:

Subject (observed)
The object being observed. When the state that needs to be observed changes, all observer objects in the queue need to be notified. Subject needs to maintain (add, delete, notify) a queue list of observer objects.
ConcreteSubject
The concrete realization of the observed person. Contains some basic attribute states and other operations.
Observer
Interface or abstract class. When the Subject's state changes, the Observer object will be notified through a callback function.
ConcreteObserver
Concrete implementation of observer. After being notified, some specific business logic processing will be completed.

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.

div.onclick = function click (){
alert ( ”click' )
}
Copy after login

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 details.

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

loadImage( imgAry, function(){
Map.init();
Gamer.init();
} )
Copy after login

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.

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

But the colleague A who wrote this module went to travel 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 think, everyone Something unsettling happened. What if we could have written it like this:

loadImage.listen( ”ready', function(){
Map.init();
})
loadImage.listen( ”ready', function(){
Gamer.init();
})
loadImage.listen( ”ready', function(){
Sount.init();
})
Copy after login

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.

loadImage.trigger( ”ready' );
Copy after login

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.

Events = function() {
var listen, log, obj, one, remove, trigger, __this;
obj = {};
__this = this;
listen = function( key, eventfn ) { //把简历扔盒子, key就是联系方式.
var stack, _ref; //stack是盒子
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() { //面试官打电话通知面试者
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
}
}
Copy after login

Finally, use the observer mode to make a small application for adult TV.

//订阅者
var adultTv = Event();
adultTv .listen( ”play', function( data ){
alert ( “今天是谁的电影” + data.name );
});
//发布者
adultTv .trigger( ”play', { ‘name': ‘麻生希' } )
Copy after login

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