Javascript is active in an event-driven environment, such as mouse response, Event Callback, and network requests. The observer mode is also called the publisher-subscriber mode, is to process the relationship between objects and their behaviors and States, and between managers and tasks. Javascript is active in an event-driven environment, such as mouse response, Event Callback, and network requests,
ObserverThe mode is also called
Publisher-subscriber ModeIs to process the relationship between objects and their behaviors and States, and between managers and tasks.
1. The most common observer pattern 1.1 event listener
document.body.addEventListener('click', function () { console.log('you clicked me, poor guy!')});
This is the simplest and most common observer mode.clickBesidesload,blur,drag,focus,mouseover. The event listener (listener) is different from the event processor (handler). In the event listener, an event can be associated with multiple listeners, and each listener independently processes the received messages; an event processor is an association function that executes processing events. An event can have a processing function:
var dom = $('.dom');var listener1 = function(e){ //do one thing}var listener2 = function(e){ //do another thing}addEvent(dom,'click',listener1);addEvent(dom,'click',listener2);
In the event listener example,listener1Andlistener2 All are dom element listeners. When dom is clicked, their respective functions are executed;
var dom = document.getElementById('dom');var handler1 = function(e){ //do one thing}var handler2 = function(e){ //do another thing}dom.onclick = handler1;dom.onclick = handler2;
In this event processor example,handler1Not executed, only executedhandler2Is a value assignment operation.
1.2 Animation
The observer mode is widely used in animation. The starting, finishing, and pausing of an animation all require the observer to determine the behavior and state of the object.
// Define the Animation var Animation = function () {this. onStart = new Publisher; // The design of Publisher will be introduced in section 1.3 this. onComplete = new Publisher; this. onTween = new Publisher;} // defines a prototype method, Animation. prototype. look = function () {this. onStart. deliver ('animation started! '); This. onTween. deliver ('animation is going on! '); This. onComplete. deliver ('animation completed! ') ;}; // Instance a box object var box = new Animation (); // defines three functions as subscribersvar openBox = function (msg) {console. log (msg)} var checkBox = function (msg) {console. log (msg)} var closeBox = function (msg) {console. log (msg)} // subscribes to the openBox event. subscribe (box. onStart); checkBox. subscribe (box. onTween); closeBox. subscribe (box. onComplete); // call method box. look () // animation started! // Animation is going on! // Animation completed!1.3 Construction of observer
First, a publisher is required. First, define a constructor and define an array for it to save the subscriber information:
function Publisher(){ this.subscribes = [];}
The publisher has the message publishing function and defines a deliver prototype function:
Publisher.prototype.deliver = function(data){ this.subscribes.forEach(function(fn){ fn(data); }); return this;}
Next we construct the subscription method:
Function.prototype.subscribe = function(publisher){ var that = this; var alreadyExists = publisher.subscribes.some(function(el){ return el === that; }); if(!alreadyExists){ publisher.subscribes.push(this); } return this;}
Add the subscribe method directly to the Function prototype so that all functions can call this method. This completes the construction. For more information about how to use this function, see the 1.2 animation use case.
A more intuitive explanationonStartFor example ):WhenboxObject executionlookMethod, runonStart.deliver(), SetonStartEvent release and broadcast notifications'animation started!'At this time, I have been listeningonStartOfopenBoxListen to the event release information and print it out.
1.4 another way to build an observer
This method imitates the node. js event processing mechanism, and the code is concise:
Var scope = (function () {// message list var events = {}; return {// subscribe to a message on: function (name, hander) {var index = 0; // if (events [name]) {// The message name already exists. Put the processing function in the event queue of the message. index = events [name]. push (hander)-1;} else {events [name] = [hander];} // return the function of removing the current Message Processing Event. return function () {events [name]. splice (index, 1) ;}}, // disable the message off: function (name) {if (! Events [name]) return; // message existence, delete message delete events [name] ;}, // message publishing emit: function (name, msg) {// message does not exist, if (! Events [name]) return; // message exists. Run events [name] Once for every function in the event processing queue. forEach (function (v, I) {v (msg) ;}}}) (); var sayHello = scope. on ('greeting ', function (msg) {console. log ('subscribe message: '+ msg) ;}); var greeting = function (msg) {console. log ('Publish message: '+ msg); scope. emit ('greeting ', msg);} greeting ('Hello Panfen! ')1.5 Implementation of observer mode in nodejs
Nodejs has the events module to implement the observer mode. For details, refer to the Nodejs API-Events to discuss the observer mode. Most modules integrate the events module, so you can directly use emit to launch events and listen to Events on, or define it as follows;
Var EventEmitter = require ('events '). eventEmitter; var life = new EventEmitter (); life. setMaxListeners (11); // sets the maximum number of listeners. The default value is 10. // publish and subscribe to sendNamelife. on ('sendname', function (name) {console. log ('Say hello to '+ name) ;}); life. emit ('sendname', 'jeff '); // publish and subscribe to sendName2function sayBeautiful (name) {console. log (name + 'is betiful');} life. on ('sendname2', sayBeautiful); life. emit ('sendname2', 'jeff ');
Common Methods:
HasConfortListener: used to determine whether a listener exists for a launch event
RemoveListener: Remove listener
ListenerCount: Total number of listeners for this event
RemoveAllListeners: removes all (or a) listeners of an event.
1.6 conclusion
The observer mode is set upPushAndListenThe logic is applicable to scenarios where we want to separate human behavior from application behavior. For example, when a user clicks a tab in the navigation bar, a sub-menu containing more options is opened. Generally, the user chooses to directly listen to the click event when he knows which element, the disadvantage of this is that it is bound directly with the click event. A better way is to create an observed onTabChange object and associate it with several observer implementations.
Related Articles:
Detailed explanation of the classic rule mode of JavaScript Design Mode
JavaScript Design Pattern classic-simple factory pattern code example
JavaScript design patterns classic Singleton patterns
The above is a detailed description of the observer mode of the javascript design mode. For more information, see other related articles in the first PHP community!