


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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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.

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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
