


Detailed explanation of the basic principles of implementing the MVVM framework in native js
This article brings you a detailed explanation of the basic principles of implementing the MVVM framework in native JS. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
In the front-end page, the Model is represented by a pure JS object, and the View is responsible for display. The two are maximized in separation.
The ViewModel is what associates the Model and the View. ViewModel is responsible for synchronizing Model data to View for display, and is also responsible for synchronizing View modifications back to Model.
The design idea of MVVM: pay attention to changes in the Model and let the MVVM framework automatically update the state of the DOM, thereby freeing developers from the cumbersome steps of operating the DOM.
After understanding the idea of MVVM, I implemented an MVVM framework using native JS.
Before implementing the MVVM framework, let’s look at a few basic usages:
Object.defineProperty
Generally declare objects, define and modify properties
1 2 3 |
|
UseObjectdefineProperty
Declare objects
Syntax:
Object.defineProperty(obj,prop,descriptor)
obj
:Required The target object to be processed
prop
: The name of the property to be defined or modified
descriptor
: The property descriptor to be defined or modified
1 2 3 4 |
|
At first glance, it seems a bit superfluous. Isn’t it useless?
Don’t worry, look down
Descriptor
descriptor
There are two forms: data descriptor and storage descriptor. They both share attributes:
configurable
, whether it can be deleted, the default is false
, it cannot be defined after Modify
enumerable
, whether it can be traversed, the default is false
, the
shared attributes
cannot be modified in the future. When configurable
is set to false
, its internal properties cannot be deleted using delete
; if you want to delete, you need to set configurable
to true
. When
1 2 3 4 5 6 |
|
enumerable
is set to false
, its internal properties cannot be traversed; if traversal is required, set enumerable
to true
1 2 3 4 5 6 7 8 |
|
Data descriptor
value
: The value corresponding to this attribute, the default is undefined
. writable
: When and immediately if it is true
, value
can be changed by the assignment operator. Default is false
. The difference between
1 2 3 4 5 6 7 |
|
writable
and configurable
is that the former is whether value
can be modified, and the latter is whether value
can be deleted.
Storage descriptor
get()
: A method that provides a getter
for a property, defaulting to undefined
. set()
: A method that provides setter
for the property. The default is undefined
.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
When I call obj.age
, I am actually asking the obj
object for the age
attribute. What will it do? It will call the obj.get()
method, which will find the global variable age
and get undefined
.
When I set obj.age = 20
, it calls the obj.set()
method, setting the global variable age
to 20
.
At this time, when calling obj.age
, we get 20
.
Note: Data descriptor and storage descriptor cannot exist at the same time, otherwise an error will be reported
1 2 3 4 5 6 7 8 9 10 11 |
|
Data interception
Use Object.defineProperty
To implement data interception and data monitoring.
First there is an object
1 2 3 4 |
|
Write a function below to monitor the data
object, and then you can do some things internally
1 |
|
Change In other words, the internal attributes of data
are all monitored by us. When calling the attribute, we can do some tricks on it to change the returned value; when setting the attribute, we will not set it.
Of course this is boring, but I just want to show that we can do things internally to achieve the results we want.
Thenobserve
How should I write this function?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
Note two points:
We cannot use
var
when declaringlet val = data[key]
, because each attribute needs to be monitored here, usinglet
will create a newval
for each traversal, and then assign the value; if usingvar
, only The first time is the declaration, and the following are all assignments to the declarationval
. After the traversal is completed, the last attribute is obtained, which is obviously not what we need.get
In the method,return
is theval
declared earlier.data[key cannot be used here ]
, an error will be reported. Because callingdata.name
means calling theget
method, the result isdata.name
, and then continues to call theget
method, It becomes an infinite loop, so here you need to use a variable to storedata[key]
, and return this variable.
Observer Mode
A typical observer mode application scenario - WeChat public account
不同的用户(我们把它叫做观察者:Observer)都可以订阅同一个公众号(我们把它叫做主体:Subject)
当订阅的公众号更新时(主体),用户都能收到通知(观察者)
用代码怎么实现呢?先看逻辑:
Subject 是构造函数,new Subject()创建一个主题对象,它维护订阅该主题的一个观察者数组数组(举例来说:Subject 是腾讯推出的公众号,new Subject() 是一个某个机构的公众号——新世相,它要维护订阅这个公众号的用户群体)
主题上有一些方法,如添加观察者addObserver
、删除观察者removeObserver
、通知观察者更新notify
(举例来说:新世相将用户分为两组,一组是忠粉就是 addObserver,一组是黑名单就是:removeObserver,它在忠粉组可以添加用户,可以在黑名单里拉黑一些杠精,如果有福利发放,它就会统治忠粉里的用户:notify)
Observer 是构造函数,new Observer() 创建一个观察者对象,该对象有一个update
方法(举例来说:Observer 是忠粉用户群体,new Observer() 是某个具体的用户——小王,他必须要打开流量才能收到新世相的福利推送:updata)
当调用notify
时实际上调用全部观察者observer
自身的update
方法(举例来说:当新世相推送福利时,它会自动帮忠粉组的用户打开流量,这比较极端,只是用来举例)
ES5 写法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
|
ES6 写法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
|
ES5 和 ES6 写法效果一样,ES5 的写法更好理解,ES6 只是个语法糖
主题添加观察者的方法subject.addObserver(observer)
很繁琐,直接给观察者下方权限,给他们增加添加进忠粉组的权限
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
MVVM 框架的内部基本原理就是上面这些。
相关推荐:
The above is the detailed content of Detailed explanation of the basic principles of implementing the MVVM framework in native js. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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

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

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.

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

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
