Home  >  Article  >  Web Front-end  >  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

不言
不言Original
2018-09-01 17:35:232683browse

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

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

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.

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

  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 写法:

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 框架的内部基本原理就是上面这些。

相关推荐:

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