Table of Contents
Object.defineProperty
Descriptor
shared attributes
Data descriptor
Storage descriptor
Data interception
Observer Mode
ES6 写法:
Home Web Front-end JS Tutorial Detailed explanation of the basic principles of implementing the MVVM framework in native js

Detailed explanation of the basic principles of implementing the MVVM framework in native js

Sep 01, 2018 pm 05:35 PM
javascript

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

let obj = {}

obj.name = 'zhangsan'

obj.age = 20

Copy after login

UseObjectdefinePropertyDeclare 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

let obj = {}

Object.defineProperty(obj,'age',{

    value = 14,

})

Copy after login

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

let obj = {}

Object.defineProperty(obj,'age',{

    configurable:false,

    value:20,

})

delete obj.age         //false

Copy after login

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

let obj = {name:'zhangsan'}

Object.defineProperty(obj,'age',{

    enumerable:false,

    value:20,

})

for(let key in obj){

    console.log(key)    //name

}

Copy after login

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

let obj = {}

Object.defineProperty(obj,'age',{

    value:10,

    writable:false

})

obj.age = 11

obj.age        //10

Copy after login

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

let obj = {}

let age

Object.defineProperty(obj,'age',{

    get:function(){

        return age

    },

    set:function(newVal){

        age = newVal

    }

})

obj.age = 20

obj.age        //20

Copy after login

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

let obj = {}

let age

Object.defineProperty(obj,'age',{

    value:10,        //报错

    get:function(){

        return age

    },

    set:function(newVal){

        age = newVal

    }

})

Copy after login

Data interception

Use Object.defineProperty To implement data interception and data monitoring.

First there is an object

1

2

3

4

let data = {

    name:'zhangsan',

    friends:[1,2,3,4]

}

Copy after login

Write a function below to monitor the data object, and then you can do some things internally

1

observe(data)

Copy after login

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.

ThenobserveHow 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

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    //这里注释掉了,实际设置属性就是这样写的。

            }

        })

    }

}

Copy after login

Note two points:

  1. We cannot use var when declaring let val = data[key] , because each attribute needs to be monitored here, using let will create a new val for each traversal, and then assign the value; if using var, only The first time is the declaration, and the following are all assignments to the declaration val. After the traversal is completed, the last attribute is obtained, which is obviously not what we need.

  2. getIn the method, return is the val declared earlier. data[key cannot be used here ], an error will be reported. Because calling data.name means calling the get method, the result is data.name, and then continues to call the get method, It becomes an infinite loop, so here you need to use a variable to store data[key], and return this variable.

Observer Mode

A typical observer mode application scenario - WeChat public account

  1. 不同的用户(我们把它叫做观察者:Observer)都可以订阅同一个公众号(我们把它叫做主体:Subject)

  2. 当订阅的公众号更新时(主体),用户都能收到通知(观察者)

用代码怎么实现呢?先看逻辑:

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

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

Copy after login

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

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

Copy after login

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

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

Copy after login

MVVM 框架的内部基本原理就是上面这些。

相关推荐:

js实现一个简单的MVVM框架示例分享

PHP的MVC框架 深入解析_PHP教程

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!

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 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months 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.

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

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.

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

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

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

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

See all articles