


Detailed introduction to the observer pattern of JavaScript design patterns
Javascript is active in an event-driven environment, such as mouse response, event callback, network request, etc. Observer
mode is also called publisher-subscriber (publisher-subscriber) Pattern
deals with the relationship between objects, their behaviors and states, and manages the relationship between people 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 pattern, except click In addition to
, there are also load
, blur
, drag
, focus
, mouseover
, etc. An event listener (listener) is different from an event handler (handler). In an event listener, an event can be associated with multiple listeners, and each listener independently processes the monitored message; the event handler is responsible for executing and processing the event. After the associated function, 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 this example of the event listener, listener1
and listener2
are both dom elements The listeners will execute their respective functions when the dom is clicked;
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 the example of this event handler, handler1
will not be executed, only handler2
is an assignment operation.
1.2 Animation
The observer mode is widely used in animation. The start, completion, pause, etc. of animation require an observer to determine the behavior and status of the object.
//定义动画 var Animation = function(){ this.onStart = new Publisher; //关于Publisher的设计将在1.3节介绍 this.onComplete = new Publisher; this.onTween = new Publisher; } //定义一个原型方法 Animation.prototype.look = function(){ this.onStart.deliver('animation started!'); this.onTween.deliver('animation is going on!'); this.onComplete.deliver('animation completed!'); }; //实例一个box对象 var box = new Animation(); //定义三个函数作为subscribers var openBox = function(msg){ console.log(msg) } var checkBox = function(msg){ console.log(msg) } var closeBox = function(msg){ console.log(msg) } //订阅事件 openBox.subscribe(box.onStart); checkBox.subscribe(box.onTween); closeBox.subscribe(box.onComplete); //调用方法 box.look() //animation started! //animation is going on! //animation completed!
1.3 Construction of Observer
First, a publisher is needed. First define a constructor and an array for it to save subscriber information:
function Publisher(){ this.subscribes = []; }
The publisher has the function of publishing messages, and defines a prototype function of deliver:
Publisher.prototype.deliver = function(data){ this.subscribes.forEach(function(fn){ fn(data); }); return this; }
Next Construct a 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. In this way, the construction is completed. For usage methods, please refer to the use case of 1.2 Animation.
A more intuitive explanation (take onStart
as an example): When the box
object executes the look
method, execute onStart.deliver()
, publishes the onStart
event and broadcasts the notification 'animation started!'
. At this time, it has been monitoring onStart
openBox
Listen to the information released by the event and print it out.
1.4 Another way to build an observer
This method imitates the event processing mechanism of nodejs, and the code is relatively concise:
var scope = (function() { //消息列表 var events = {}; return { //订阅消息 on:function(name,hander){ var index = 0; //记录消息时间的索引 if(events[name]){ //消息名已存在,将处理函数放到该消息的事件队列中 index = events[name].push(hander) - 1; }else{ events[name] = [hander]; } //返回当前消息处理事件的移除函数 return function(){ events[name].splice(index,1); } }, //关闭消息 off:function(name){ if(!events[name]) return; //消息存在,删除消息 delete events[name]; }, //消息发布 emit:function(name,msg){ //消息不存在,不处理 if(!events[name]) return; //消息存在,将该事件处理队列中每一个函数都执行一次 events[name].forEach(function(v,i){ v(msg); }); } } })(); var sayHello = scope.on('greeting',function(msg){ console.log('订阅消息:' + msg); }); var greeting = function(msg){ console.log('发布消息:' + msg); scope.emit('greeting', msg); } greeting('hello Panfen!')
1.5 Observer mode in nodejs Implementation plan
There is an events module in nodejs to implement the observer mode. You can refer to Nodejs API-Events to talk about the observer mode. Most modules integrate the events module, so you can directly use emit to launch events and on Listen for events, or define it first like below;
var EventEmitter = require('events').EventEmitter; var life = new EventEmitter(); life.setMaxListeners(11); //设置最大监听数,默认10 //发布和订阅sendName life.on('sendName',function(name){ console.log('say hello to '+name); }); life.emit('sendName','jeff'); //发布和订阅sendName2 function sayBeautiful(name){ console.log(name + ' is beautiful'); } life.on('sendName2',sayBeautiful); life.emit('sendName2','jeff');
Common methods:
hasConfortListener: Used to determine whether the emitted event has a listener
removeListener: Remove the listener
listenerCount: The total number of all listeners for this event
removeAllListeners: Remove All (or one) event listeners
pushand
listen The logic is suitable for situations where you want to separate human behavior from application behavior. For example: when the user clicks a tab on the navigation bar, a submenu containing more options will open. Generally, the user will choose to listen to the click event directly if he knows which element. The disadvantage of this is that it is not the same as the click event. The events are directly tied together. A better approach is to create an observable onTabChange object and associate several observer implementations.
Detailed explanation of the classic JavaScript design pattern, the strategy pattern
##The classic JavaScript design pattern, the simple factory pattern code exampleDetailed Explanation of the Classic Singleton Pattern of JavaScript Design PatternsThe above is the detailed content of Detailed introduction to the observer pattern of JavaScript design patterns. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment