Home Web Front-end JS Tutorial An in-depth explanation of the observer pattern in Javascript (graphic tutorial)

An in-depth explanation of the observer pattern in Javascript (graphic tutorial)

May 19, 2018 am 11:38 AM
javascript js

The observer pattern, also known as the publish-subscribe pattern, is one of the most commonly used design patterns. The following article mainly gives you an in-depth introduction to the relevant materials of the observer pattern in Javascript.

Introduction

The observer pattern is also called publish/subscribe pattern (Publish/Subscribe). It defines a one-to-many relationship, allowing multiple observer objects to At the same time, a certain topic object is monitored. When the status of this topic object changes, all observer objects will be notified, so that they can automatically update themselves. To be honest, if we were not writing slightly low-level code, we might not use it. But having it will make the code more flexible and regular, reduce redundant code, and facilitate the development of modules and functions.

Benefits of using the observer pattern:

  1. Supports simple broadcast communication and automatically notifies all subscribed objects.

  2. After the page is loaded, the target object can easily have a dynamic relationship with the observer, which increases flexibility.

  3. The abstract coupling relationship between the target object and the observer can be independently extended and reused.

Introduction

In front-end business, the place that may be used more may be custom events.
In fact, the events of the browser are also observer mode

p.onclick = function click() {
 console.log('click')
}
Copy after login

Here function click subscribes to the click event of p. When our mouse clicks, the event is published , the corresponding function will be executed. This function click is an observer.

Concrete understanding

In fact, you can understand it simply by looking at the code implementation. But everything is connected. The design of these programming models also comes from life experience. Therefore, concrete understanding is also a very important experience.

Let’s take an example of a wedding banquet. For example, a good friend of yours is getting married. "Getting married" doesn't happen every day, it only happens once or twice in a lifetime (maybe more). So our "going to his wedding" definitely doesn't happen every day, but only on certain occasions. when. I definitely can't ask him every day, 'Are you getting married today? I'll come to the banquet.' Once or twice is okay, ask every day, sb. If you are a single guy who can't find a partner, and you ask this question every day, he won't kill you. .

Then there needs to be an event released here, which is to 'notify you'.

As an observer, I subscribed to the event of his 'marriage'. We are good friends and I will definitely go to his wedding. We have already agreed. Then I am the observer, and 'I go to the wedding' is the corresponding action. When I subscribe to the 'marriage' event, I don't need to ask him every day, what should I do, pick up girls, make dinner dates, watch movies, date... whatever.

When he posted the event of 'marriage', the notification was sent to me, and I went to do the 'attend the wedding banquet' function at a specific time...

//模拟代码
//我订阅了'marry' 事件
wo.on('marry',function(){
 //去参加婚礼酒席
})
//然后他发布。比如浏览器的点击
// 对应的我的 function就会执行
Copy after login

Decoupling/Module/Function

In fact, in the code, an intermediary similar to an intermediate service is needed to manage publishing and subscription.

For example, the event handler in the browser provides a subscription interface, and then receives the 'event' signal and publishes it to you. Let the js code have contact and interaction with the browser. But originally they were two different things.

In my opinion, the biggest benefit of the observer pattern is decoupling, which will allow us to separate the code into functions and modules, making it clearer, lower development costs, and easier to maintain.

For example:

1. For the view display layer and model (data processing) logic layer in our project, we first write the page, ajax, string splicing, and request an interface. Fight it and give it to dom. Maybe we have a js file and a function that requests an interface and is responsible for the display of the view.

var xhr = new XMLHttpRequest ()
 xhr.open('get',url)
 xhr.onreadystatechange = function () {
 if(this.readyState !== 4) return
 if(this.status === 200) {
 ps.innerHTML = &#39;<p>&#39; + this.response + &#39;</p>&#39;
 //
 }
 }
 xhr.responseType = &#39;json&#39;
 xhr.send(null)
Copy after login

In fact, the request should be separated from the display rendering.

//请求
function getData () {
 var xhr = new XMLHttpRequest ()
 xhr.open(&#39;get&#39;,url)
 xhr.onreadystatechange = function () {
 if(this.readyState !== 4) return
 if(this.status === 200) {
 this.emit(&#39;渲染&#39;)
 // 发布
 }
 }
 xhr.responseType = &#39;json&#39;
 xhr.send(null)
}
//渲染
function view () {}
xhr.on(&#39;渲染&#39;,view)
Copy after login

It can also be done by placing a callback directly on the status code 200. But if I have two render functions that handle different things, do I have to change them to different functions each time? Do I have to write the same request process again?

In the words of an observer

function view1 () {}
function view2 () {}
function view3 () {}
function view4 () {}
if(我要渲染view1) {
 xhr.on(&#39;渲染&#39;,view1) //订阅
 xhr.on(&#39;渲染&#39;,view2)
}else{
 xhr.on(&#39;渲染&#39;,view3)
 xhr.on(&#39;渲染&#39;,view4)
}
Copy after login

The advantage lies in my getData function. The method is only responsible for requesting data, and then he An interface will be exposed for me to add methods. In this way, my getData is a relatively complete functional module. No matter how many situations I encounter, the code in my getData will not change.

Sometimes we often change the code we wrote before in order to implement business and add a new function, causing our original functional modules to be changed beyond recognition.

And there will be a lot of duplicate code.

process? or module?

Of course it is very difficult to seal a good and complete functional module, but we must at least have a start.

Subscribe to add methods, and execute them when the event pool is published.

2. MV* class framework

MVC也是一种设计模式,这里面也都应用了观察者。

他内部也都是各种发布订阅,好像是一个观察者模型,从而实现了一个模拟的内存中的dom改变,计算出那个DOM节点应该改变。当然具体实现要做好多事情…就不…

3、redux

简单实现一个createstore函数

//这是一个工厂函数,可以创建store
const createStore = (reducer) => {
 let state; // 定义存储的state
 let listeners = [];
 // getState的作用很简单就是返回当前是state
 const getState = ()=> state;
 //定义一个派发函数
 //当在外界调用此函数的时候,会修改状态
 const dispatch = (action)=>{
 //调用reducer函数修改状态,返回一新的状态并赋值给这个局部状态变量
 state = reducer(state,action);
 //依次调用监听函数,通知所有的监听函数
 listeners.forEach(listener => listener());
 }
 //订阅此状态的函数,当状态发生变化的时候记得调用此监听函数
 const subscribe = function(listener){
 //先把此监听 加到数组中
 listeners.push(listener);
 //返回一个函数,当调用它的时候将此监听函数从监听数组移除
 return function(){
  listeners = listeners.filter(l => l != listener);
 }
 }
 //默认调用一次dispatch给state赋一个初始值
 dispatch();
 return {
 getState,
 dispatch,
 subscribe
 }
}
let store = createStore(reducer);
//把数据渲染到界面上
const render = () => {
 document.body.innerText = store.getState();
}
// 订阅状态变化事件,当状态变化时用监听函数
store.subscribe(render);
render();
var INCREASE_ACTION = {type: &#39;INCREMENT&#39;};
document.addEventListener(&#39;click&#39;, function (e) {
 //触发一个Action
 store.dispatch(INCREASE_ACTION);
})
Copy after login

4、在node 中的作用 大多数时候我们不会直接使用 EventEmitter,而是在对象中继承它。包括fs、net、 http 在内的,只要是支持事件响应的核心模块都是 EventEmitter 的子类。

实现一个可以发布订阅的类

&#39;use strict&#39;
class EmitterEvent {
 constructor() {
 //构造器。实例上创建一个事件池
 this._event = {}
 }
 //on 订阅
 on (eventName, handler) {
 // 根据eventName,事件池有对应的事件数组,
 就push添加,没有就新建一个。
 // 严谨一点应该判断handler的类型,是不是function
 if(this._event[eventName]) {
 this._event[eventName].push(handler)
 } else {
 this._event[eventName] = [handler]
 }
 }
 emit (eventName) {
 // 根据eventName找到对应数组
 var events = this._event[eventName];
 // 取一下传进来的参数,方便给执行的函数
 var otherArgs = Array.prototype.slice.call(arguments,1)
 var that = this
 if(events) {
 events.forEach((event) => {
 event.apply(that, otherArgs)
 })
 }
 }
 // 解除订阅
 off (eventName, handler) {
 var events = this._event[eventName]
 if(events) {
 this._event[eventName] = events.filter((event) => {
 return event !== handler
 })
 }
 }
 // 订阅以后,emit 发布执行一次后自动解除订阅
 once (eventName, handler) {
 var that = this
 function func () {
 var args = Array.prototype.slice.call(arguments,0)
 handler.apply(that, args)
 this.off(eventName,func)
 }
 this.on(eventName, func)
 }
}
var event = new EmitterEvent()
function a (something) {
 console.log(something,&#39;aa-aa&#39;)
}
function b (something) {
 console.log(something)
}
 event.once(&#39;dosomething&#39;,a)
 event.emit(&#39;dosomething&#39;, &#39;chifan&#39;)
 //event.emit(&#39;dosomething&#39;)
// event.on(&#39;dosomething&#39;,a)
// event.on(&#39;dosomething&#39;,b)
// event.emit(&#39;dosomething&#39;,&#39;chifan&#39;)
// event.off(&#39;dosomething&#39;,a)
// setTimeout(() => {
// event.emit(&#39;dosomething&#39;,&#39;hejiu&#39;)
// },2000)
Copy after login

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

JS DOM元素常见增删改查操作详解

JS刷新页面方法总结

JS callback回调函数使用案例详解

The above is the detailed content of An in-depth explanation of the observer pattern in Javascript (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

See all articles