MVVM模式相信作前端的人都不陌生,去网上搜MVVM,会出现一大堆关于MVVM模式的博文,可是这些博文大多都只是用图片和文字来进行抽象的概念讲解,对于刚接触MVVM模式的新手来讲,这些概念虽然可以读懂,可是也很难作到理解透彻。所以,我写了这篇文章。javascript
这篇文章旨在经过代码的形式让你们更好的理解MVVM模式,相信大多数人读了这篇文章以后再去看其余诸如regular、vue等基于MVVM模式框架的源码,会容易不少。前端
若是你对MVVM模式已经很熟悉而且也已经研读过并深入理解了当下主流的前端框架,能够忽略下面的内容。若是你没有一点JavaScript基础,也请先去学习下再来阅读读此文。vue
来张图来镇压此文:java
MVVM
是Model-View-ViewModel
的缩写。简单的讲,它将View
与Model
层分隔开,利用ViewModel
层将Model
层的数据通过必定的处理变成适用于View
层的数据结构并传送到View
层渲染界面,同时View
层的视图更新也会告知ViewModel
层,而后ViewModel
层再更新Model
层的数据。算法
咱们用一段学生信息的代码做为引子,而后一步步再重构成MVVM模式的样子。前端框架
编写相似下面结构的学生信息:数据结构
- Name: Jessica Bre
- Height: 1.8m
- Weight: 70kg
用常规的js代码是这样的:app
const student = { 'first-name': 'Jessica', 'last-name': 'Bre', 'height': 180, 'weight': 70, } const root = document.createElement('ul') const nameLi = document.createElement('li') const nameLabel = document.createElement('span') nameLabel.textContent = 'Name: ' const name_ = document.createElement('span') name_.textContent = student['first-name'] + ' ' + student['last-name'] nameLi.appendChild(nameLabel) nameLi.appendChild(name_) const heightLi = document.createElement('li') const heightLabel = document.createElement('span') heightLabel.textContent = 'Height: ' const height = document.createElement('span') height.textContent = '' + student['height'] / 100 + 'm' heightLi.appendChild(heightLabel) heightLi.appendChild(height) const weightLi = document.createElement('li') const weightLabel = document.createElement('span') weightLabel.textContent = 'Weight: ' const weight = document.createElement('span') weight.textContent = '' + student['weight'] + 'kg' weightLi.appendChild(weightLabel) weightLi.appendChild(weight) root.appendChild(nameLi) root.appendChild(heightLi) root.appendChild(weightLi) document.body.appendChild(root)
好长的一堆代码呀!别急,下面咱们一步步优化!框架
程序设计中最普遍接受的规则之一就是“DRY”: "Do not Repeat Yourself"。很显然,上面的一段代码有不少重复的部分,不只与这个准则相违背,并且给人一种不舒服的感受。是时候作下处理,来让这段学生信息更"Drier"。dom
能够发现,代码里写了不少遍document.createElement
来建立节点,可是因为列表项都是类似的结构,因此咱们没有必要一遍一遍的写。所以,进行以下封装:
const createListItem = function (label, content) { const li = document.createElement('li') const labelSpan = document.createElement('span') labelSpan.textContent = label const contentSpan = document.createElement('span') contentSpan.textContent = content li.appendChild(labelSpan) li.appendChild(contentSpan) return li }
通过这步转化以后,整个学生信息应用就变成了这样:
const student = { 'first-name': 'Jessica', 'last-name': 'Bre', 'height': 180, 'weight': 70, } const createListItem = function (label, content) { const li = document.createElement('li') const labelSpan = document.createElement('span') labelSpan.textContent = label const contentSpan = document.createElement('span') contentSpan.textContent = content li.appendChild(labelSpan) li.appendChild(contentSpan) return li } const root = document.createElement('ul') const nameLi = createListItem('Name: ', student['first-name'] + ' ' + student['last-name']) const heightLi = createListItem('Height: ', student['height'] / 100 + 'm') const weightLi = createListItem('Weight: ', student['weight'] + 'kg') root.appendChild(nameLi) root.appendChild(heightLi) root.appendChild(weightLi) document.body.appendChild(root)
是否是变得更短了,也更易读了?即便你不看createListItem
函数的实现,光看const nameLi = createListItem('Name: ', student['first-name'] + ' ' + student['last-name'])
也能大体明白这段代码时干什么的。
可是上面的代码封装的还不够,由于每次建立一个列表项,咱们都要多调用一遍createListItem
,上面的代码为了建立name,height,weight
标签,调用了三遍createListItem
,这里显然还有精简的空间。所以,咱们再进一步封装:
const student = { 'first-name': 'Jessica', 'last-name': 'Bre', 'height': 180, 'weight': 70, } const createList = function(kvPairs){ const createListItem = function (label, content) { const li = document.createElement('li') const labelSpan = document.createElement('span') labelSpan.textContent = label const contentSpan = document.createElement('span') contentSpan.textContent = content li.appendChild(labelSpan) li.appendChild(contentSpan) return li } const root = document.createElement('ul') kvPairs.forEach(function (x) { root.appendChild(createListItem(x.key, x.value)) }) return root } const ul = createList([ { key: 'Name: ', value: student['first-name'] + ' ' + student['last-name'] }, { key: 'Height: ', value: student['height'] / 100 + 'm' }, { key: 'Weight: ', value: student['weight'] + 'kg' }]) document.body.appendChild(ul)
有没有看到MVVM风格的影子?student
对象是原始数据,至关于Model
层;createList
建立了dom
树,至关于View
层,那么ViewModel
层呢?仔细观察,其实咱们传给createList
函数的参数就是Model
的数据的改造,为了让Model
的数据符合View
的结构,咱们作了这样的改造,所以虽然这段函数里面没有独立的ViewModel
层,可是它确实是存在的!聪明的同窗应该想到了,下一步就是来独立出ViewModel
层了吧~
// Model const tk = { 'first-name': 'Jessica', 'last-name': 'Bre', 'height': 180, 'weight': 70, } //View const createList = function(kvPairs){ const createListItem = function (label, content) { const li = document.createElement('li') const labelSpan = document.createElement('span') labelSpan.textContent = label const contentSpan = document.createElement('span') contentSpan.textContent = content li.appendChild(labelSpan) li.appendChild(contentSpan) return li } const root = document.createElement('ul') kvPairs.forEach(function (x) { root.appendChild(createListItem(x.key, x.value)) }) return root } //ViewModel const formatStudent = function (student) { return [ { key: 'Name: ', value: student['first-name'] + ' ' + student['last-name'] }, { key: 'Height: ', value: student['height'] / 100 + 'm' }, { key: 'Weight: ', value: student['weight'] + 'kg' }] } const ul = createList(formatStudent(tk)) document.body.appendChild(ul)
这看上去更舒服了。可是,最后两行还能封装~
const run = function (root, {model, view, vm}) { const rendered = view(vm(model)) root.appendChild(rendered) } run(document.body, { model: tk, view: createList, vm: formatStudent })
这种写法,熟悉vue或者regular的同窗,应该会以为似曾相识吧?
前面学生信息的身高的单位都是默认m
,若是新增一个需求,要求学生的身高的单位能够在m
和cm
之间切换呢?
首先须要一个变量来保存度量单位,所以这里必须用一个新的Model:
const tk = { 'first-name': 'Jessica', 'last-name': 'Bre', 'height': 180, 'weight': 70, } const measurement = 'cm'
为了让tk
更方便的被其余模块重用,这里选择增长一个measurement
数据源,而不是直接修改tk
。
在视图部分要增长一个radio单选表单,用来切换身高单位。
const createList = function(kvPairs){ const createListItem = function (label, content) { const li = document.createElement('li') const labelSpan = document.createElement('span') labelSpan.textContent = label const contentSpan = document.createElement('span') contentSpan.textContent = content li.appendChild(labelSpan) li.appendChild(contentSpan) return li } const root = document.createElement('ul') kvPairs.forEach(function (x) { root.appendChild(createListItem(x.key, x.value)) }) return root } const createToggle = function (options) { const createRadio = function (name, opt){ const radio = document.createElement('input') radio.name = name radio.value = opt.value radio.type = 'radio' radio.textContent = opt.value radio.addEventListener('click', opt.onclick) radio.checked = opt.checked return radio } const root = document.createElement('form') options.opts.forEach(function (x) { root.appendChild(createRadio(options.name, x)) root.appendChild(document.createTextNode(x.value)) }) return root } const createToggleableList = function(vm){ const listView = createList(vm.kvPairs) const toggle = createToggle(vm.options) const root = document.createElement('div') root.appendChild(toggle) root.appendChild(listView) return root }
接下来是ViewModel
部分,createToggleableList
函数须要与以前的createList
函数不一样的参数。所以,对View-Model结构重构是有必要的:
const createVm = function (model) { const calcHeight = function (measurement, cms) { if (measurement === 'm'){ return cms / 100 + 'm' }else{ return cms + 'cm' } } const options = { name: 'measurement', opts: [ { value: 'cm', checked: model.measurement === 'cm', onclick: () => model.measurement = 'cm' }, { value: 'm', checked: model.measurement === 'm', onclick: () => model.measurement = 'm' } ] } const kvPairs = [ { key: 'Name: ', value: model.student['first-name'] + ' ' + model.student['last-name'] }, { key: 'Height: ', value: calcHeight(model.measurement, model.student['height']) }, { key: 'Weight: ', value: model.student['weight'] + 'kg' }, { key: 'BMI: ', value: model.student['weight'] / (model.student['height'] * model.student['height'] / 10000) }] return {kvPairs, options} }
这里为createToggle
添加了ops
,而且将ops
封装成了一个对象。根据度量单位,使用不一样的方式去计算身高。当任何一个radio
被点击,数据的度量单位将会改变。
看上去很完美,可是当你点击radio标签的时候,视图不会有任何改变。由于这里尚未为视图作更新算法。有关MVVM
如何处理视图更新,那是一个比较大的课题,须要另辟一个博文来说,因为本文写的是一个精简的MVVM
框架,这里就再也不赘述,并用最简单的方式实现视图更新:
const run = function (root, {model, view, vm}) { let m = {...model} let m_old = {} setInterval( function (){ if(!_.isEqual(m, m_old)){ const rendered = view(vm(m)) root.innerHTML = '' root.appendChild(rendered) m_old = {...m} } },1000) } run(document.body, { model: {student:tk, measurement}, view: createToggleableList, vm: createVm })
上述代码引用了一个外部库lodash
的isEqual
方法来比较数据模型是否有更新。此段代码应用了轮询,每秒都会检测数据是否发生变化,有变化了再更新视图。这是最笨的方法,而且在DOM结构比较复杂时,性能也会受到很大的影响。仍是一样的话,本文的主题是一个精简的MVVM框架,所以略去了不少细节性的东西,只把主要的东西提炼出来,以达到更好的理解MVVM模式的目的。
以上即是一个简短精简的MVVM风格的学生信息的示例。至此,一个精简的MVVM框架其实已经出来了:
/** * @param {Node} root * @param {Object} model * @param {Function} view * @param {Function} vm */ const run = function (root, {model, view, vm}) { let m = {...model} let m_old = {} setInterval( function (){ if(!_.isEqual(m, m_old)){ const rendered = view(vm(m)) root.innerHTML = '' root.appendChild(rendered) m_old = {...m} } },1000) }
什么?你肯定不是在开玩笑?一个只有十行的框架?请记住:
框架是对如何组织代码和整个项目如何通用运做的抽象。
这并不意味着你应该有一堆代码或混乱的类,尽管企业可用的API列表常常都很可怕的长。可是若是你研读一个框架仓库的核心文件夹,你可能发现它会出乎意料的小(相比于整个项目来讲)。其核心代码包含主要工做进程,而其余部分只是帮助开发人员以更加温馨的方式构建应用程序的附件。有兴趣的同窗能够去看看cycle.js,这个框架只有124行(包含注释和空格)。
此时用一张图来做为总结再好不过了!
固然这里还有不少细节须要进一步探讨,好比如何选择或设计一个更加友好的View层的视图工具,如何更新和什么时候更新视图比较合适等等。若是把这些问题都解决了,相信这种MVVM框架会更加健壮。