


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
let obj = {} obj.name = 'zhangsan' obj.age = 20
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
let obj = {} Object.defineProperty(obj,'age',{ value = 14, })
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
let obj = {} Object.defineProperty(obj,'age',{ configurable:false, value:20, }) delete obj.age //false
enumerable
is set to false
, its internal properties cannot be traversed; if traversal is required, set enumerable
to true
let obj = {name:'zhangsan'} Object.defineProperty(obj,'age',{ enumerable:false, value:20, }) for(let key in obj){ console.log(key) //name }
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
let obj = {} Object.defineProperty(obj,'age',{ value:10, writable:false }) obj.age = 11 obj.age //10
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
.
let obj = {} let age Object.defineProperty(obj,'age',{ get:function(){ return age }, set:function(newVal){ age = newVal } }) obj.age = 20 obj.age //20
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
let obj = {} let age Object.defineProperty(obj,'age',{ value:10, //报错 get:function(){ return age }, set:function(newVal){ age = newVal } })
Data interception
Use Object.defineProperty
To implement data interception and data monitoring.
First there is an object
let data = { name:'zhangsan', friends:[1,2,3,4] }
Write a function below to monitor the data
object, and then you can do some things internally
observe(data)
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?
function observe(data){ if(!data || typeof data !== 'object')return //如果 data 不是对象,什么也不做,直接跳出,也就是说只对 对象 操作 for(let key in data){ //遍历这个对象 let val = data[key] //得到这个对象的每一个`value` if(typeof val === 'object'){ //如果这个 value 依然是对象,用递归的方式继续调用,直到得到基本值的`value` observe(val) } Object.defineProperty(data,key,{ //定义对象 configurable:true, //可删除,原本的对象就能删除 enumerable:true, //可遍历,原本的对象就能遍历 get:function(){ console.log('这是假的') //调用属性时,会调用 get 方法,所以调用属性可以在 get 内部做手脚 //return val //这里注释掉了,实际调用属性就是把值 return 出去 }, set:function(newVal){ console.log('我不给你设置。。。') //设置属性时,会调用 set 方法,所以设置属性可以在 set 内部做手脚 //val = newVal //这里注释掉了,实际设置属性就是这样写的。 } }) } }
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 写法:
function Subject(){ this.observers = [] } Subject.prototype.addObserver = function(observer){ this.observers.push(observer) } Subject.prototype.removeObserver = function(observer){ let index = this.observers.indexOf(observer) if(index > -1){ this.observers.splice(index,1) } } Subject.prototype.notify = function(){ this.observers.forEach(observer=>{ observer.update() }) } function Observer(name){ this.name = name this.update = function(){ console.log(name + ' update...') } } let subject = new Subject() //创建主题 let observer1 = new Observer('xiaowang') //创建观察者1 subject.addObserver(observer1) //主题添加观察者1 let observer2 = new Observer('xiaozhang') //创建观察者2 subject.addObserver(observer2) //主题添加观察者2 subject.notify() //主题通知观察者 /**** 输出 *****/ hunger update... valley update...
ES6 写法:
class Subject{ constructor(){ this.observers = [] } addObserver(observer){ this.observers.push(observer) } removeObserver(observer){ let index = this.observers.indexOf(observer) if(index > -1){ this.observers.splice(index,1) } } notify(){ this.observers.forEach(observer=>{ observer.update() }) } } class Observer{ constructor(name){ this.name = name this.update = function(){ console.log(name + ' update...') } } } let subject = new Subject() //创建主题 let observer1 = new Observer('xiaowang') //创建观察者1 subject.addObserver(observer1) //主题添加观察者1 let observer2 = new Observer('xiaozhang') //创建观察者2 subject.addObserver(observer2) //主题添加观察者2 subject.notify() //主题通知观察者 /**** 输出 *****/ hunger update... valley update...
ES5 和 ES6 写法效果一样,ES5 的写法更好理解,ES6 只是个语法糖
主题添加观察者的方法subject.addObserver(observer)
很繁琐,直接给观察者下方权限,给他们增加添加进忠粉组的权限
class Observer{ constructor() { this.update = function() { console.log(name + ' update...') } } subscribeTo(subject) { //只要用户订阅了主题就会自动添加进忠粉组 subject.addObserver(this) //这里的 this 是 Observer 的实例 } } let subject = new Subject() let observer = new Observer('lisi') observer.subscribeTo(subject) //观察者自己订阅忠粉分组 subject.notify() /****** 输出 *******/ lisi update...
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

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

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











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

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
