Recommended reading:
Implementing very simple js two-way data binding
MVVM is a very popular development model for web front-end. Using MVVM can make our code focus more on processing business logic rather than caring about DOM operations. Currently, the famous MVVM frameworks include vue, avalon, react, etc. Each of these frameworks has its own merits, but the implementation idea is roughly the same: data binding + view refresh. Out of curiosity and a willingness to tinker, I also wrote the simplest MVVM library (mvvm.js) along this direction, with a total of more than 2,000 lines of code. The naming and usage of the instructions are similar to vue. I will share them here. Let’s talk about the implementation principle and my code organization ideas.
Organization of ideas
MVVM is conceptually a pattern that truly separates view and data logic, and ViewModel is the focus of the entire pattern. To implement ViewModel, you need to associate the data model (Model) with the view (View). The entire implementation idea can be simply summarized into 5 points:
Implement a Compiler to scan and extract instructions for each node of the element;
Implement a Parser to parse the instructions on the element, and update the intent of the instruction to the dom through a refresh function (a module specifically responsible for view refresh may be required in the middle), such as parsing the node
first obtain the value of isShow in the Model, and then change node.style.display according to isShow to control the display and hiding of the element;Implement a Watcher to connect the refresh function of each instruction in Parser with the fields of the corresponding Model;
Implement an Observer to monitor the value changes of all fields of the object. Once a change occurs, you can get the latest value and trigger a notification callback;
Use Observer to establish a monitoring of the Model in the Watcher. When a value in the Model changes, the monitoring is triggered. After the Watcher gets the new value, it calls the refresh function associated in step 2 to realize the data. The purpose of refreshing the view when changing.
Example of effect
First take a quick look at the final usage example, which is similar to the instantiation of other MVVM frameworks:
<div id="mobile-list"> <h1 v-text="title"></h1> <ul> <li v-for="item in brands"> <b v-text="item.name"></b> <span v-show="showRank">Rank: {{item.rank}}</span> </li> </ul> </div> var element = document.querySelector('#mobile-list'); var vm = new MVVM(element, { 'title' : 'Mobile List', 'showRank': true, 'brands' : [ {'name': 'Apple', 'rank': 1}, {'name': 'Galaxy', 'rank': 2}, {'name': 'OPPO', 'rank': 3} ] }); vm.set('title', 'Top 3 Mobile Rank List'); // => <h1>Top 3 Mobile Rank List</h1>
Module division
I divided MVVM into five modules to implement: Compilation module Compiler, parsing module Parser, view refresh module Updater, data subscription module Watcher and data listening module Observer. The process can be briefly described as follows: After the Compiler compiles the instructions, it passes the instruction information to the parser Parser for parsing. The Parser updates the initial value and subscribes to the Watcher for data changes. The Observer monitors the data changes and then feeds them back to the Watcher. The Watcher then notifies the change results. Updater finds the corresponding refresh function to refresh the view.
The above process is shown in the figure:
The following will introduce the basic principles of the implementation of these five modules (only the key parts of the code are posted, please go to my Github to read the complete implementation)
1. Compiler module Compiler
Compiler’s main responsibility is to scan and extract instructions for each node of the element. Because the compilation and parsing process will traverse the entire node tree multiple times, in order to improve compilation efficiency, element is first converted into a copy fragment in the form of a document fragment inside the MVVM constructor. The compilation object is this document fragment and should not be the target element. After all nodes are compiled, the document fragments are added back to the original real nodes.
vm.complieElement implements scanning and instruction extraction of all nodes of the element:
vm.complieElement = function(fragment, root) { var node, childNodes = fragment.childNodes; // 扫描子节点 for (var i = 0; i < childNodes.length; i++) { node = childNodes[i]; if (this.hasDirective(node)) { this.$unCompileNodes.push(node); } // 递归扫描子节点的子节点 if (node.childNodes.length) { this.complieElement(node, false); } } // 扫描完成,编译所有含有指令的节点 if (root) { this.compileAllNodes(); } }
The vm.compileAllNodes method will compile each node in this.$unCompileNodes (pass the instruction information to Parser). After compiling a node, remove it from the cache queue and check this.$unCompileNodes. .length When length === 0, it means that all compilation is completed and the document fragments can be appended to the real nodes.
2. Instruction parsing module Parser
When the compiler Compiler extracts the instructions of each node, it can be analyzed by the parser. Each instruction has a different parsing method. The parsing method of all instructions only needs to do two things: one is to update the data value to the view (initial state), and the other is to subscribe the refresh function to the change monitoring of the Model. Here we take parsing v-text as an example to describe the general parsing method of an instruction:
parser.parseVText = function(node, model) { // 取得 Model 中定义的初始值 var text = this.$model[model]; // 更新节点的文本 node.textContent = text; // 对应的刷新函数: // updater.updateNodeTextContent(node, text); // 在 watcher 中订阅 model 的变化 watcher.watch(model, function(last, old) { node.textContent = last; // updater.updateNodeTextContent(node, text); }); }
3. 数据订阅模块 Watcher
上个例子,Watcher 提供了一个 watch 方法来对数据变化进行订阅,一个参数是模型字段 model 另一个是回调函数,回调函数是要通过 Observer 来触发的,参数传入新值 last 和 旧值 old , Watcher 拿到新值后就可以找到 model 对应的回调(刷新函数)进行更新视图了。model 和 刷新函数是一对多的关系,即一个 model 可以有任意多个处理它的回调函数(刷新函数),比如: v-text="title" 和 v-html="title" 两个指令共用一个数据模型字段。
添加数据订阅 watcher.watch 实现方式为:
watcher.watch = function(field, callback, context) { var callbacks = this.$watchCallbacks; if (!Object.hasOwnProperty.call(this.$model, field)) { console.warn('The field: ' + field + ' does not exist in model!'); return; } // 建立缓存回调函数的数组 if (!callbacks[field]) { callbacks[field] = []; } // 缓存回调函数 callbacks[field].push([callback, context]); }
当数据模型的 field 字段发生改变时,Watcher 就会触发缓存数组中订阅了 field 的所有回调。
4. 数据监听模块 Observer
Observer 是整个 mvvm 实现的核心基础,看过有一篇文章说 O.o (Object.observe) 将会引爆数据绑定革命,给前端带来巨大影响力,不过很可惜,ES7 草案已经将 O.o 给废弃了!目前也没有浏览器支持!所幸的是还有 Object.defineProperty 通过拦截对象属性的存取描述符(get 和 set) 可以模拟一个简单的 Observer :
// 拦截 object 的 prop 属性的 get 和 set 方法 Object.defineProperty(object, prop, { get: function() { return this.getValue(object, prop); }, set: function(newValue) { var oldValue = this.getValue(object, prop); if (newValue !== oldValue) { this.setValue(object, newValue, prop); // 触发变化回调 this.triggerChange(prop, newValue, oldValue); } } });
然后还有个问题就是数组操作 ( push, shift 等) 该如何监测?所有的 MVVM 框架都是通过重写该数组的原型来实现的:
observer.rewriteArrayMethods = function(array) { var self = this; var arrayProto = Array.prototype; var arrayMethods = Object.create(arrayProto); var methods = 'push|pop|shift|unshift|splice|sort|reverse'.split('|'); methods.forEach(function(method) { Object.defineProperty(arrayMethods, method, function() { var i = arguments.length; var original = arrayProto[method]; var args = new Array(i); while (i--) { args[i] = arguments[i]; } var result = original.apply(this, args); // 触发回调 self.triggerChange(this, method); return result; }); }); array.__proto__ = arrayMethods; }
这个实现方式是从 vue 中参考来的,觉得用的很妙,不过数组的 length 属性是不能够被监听到的,所以在 MVVM 中应避免操作 array.length
5. 视图刷新模块 Updater
Updater 在五个模块中是最简单的,只需要负责每个指令对应的刷新函数即可。其他四个模块经过一系列的折腾,把最后的成果交给到 Updater 进行视图或者事件的更新,比如 v-text 的刷新函数为:
updater.updateNodeTextContent = function(node, text) { node.textContent = text; }
v-bind:style 的刷新函数:
updater.updateNodeStyle = function(node, propperty, value) { node.style[propperty] = value; }
双向数据绑定的实现
表单元素的双向数据绑定是 MVVM 的一个最大特点之一:
其实这个神奇的功能实现原理也很简单,要做的只有两件事:一是数据变化的时候更新表单值,二是反过来表单值变化的时候更新数据,这样数据的值就和表单的值绑在了一起。
数据变化更新表单值利用前面说的 Watcher 模块很容易就可以做到:
watcher.watch(model, function(last, old) { input.value = last; });'
表单变化更新数据只需要实时监听表单的值得变化事件并更新数据模型对应字段即可:
var model = this.$model; input.addEventListenr('change', function() { model[field] = this.value; });‘
其他表单 radio, checkbox 和 select 都是一样的原理。
以上,整个流程以及每个模块的基本实现思路都讲完了,第一次在社区发文章,语言表达能力不太好,如有说的不对写的不好的地方,希望大家能够批评指正!
结语
折腾这个简单的 mvvm.js 是因为原来自己的框架项目中用的是 vue.js 但是只是用到了它的指令系统,一大堆功能只用到四分之一左右,就想着只是实现 data-binding 和 view-refresh 就够了,结果没找这样的 javascript 库,所以我自己就造了这么一个轮子。
虽说功能和稳定性远不如 vue 等流行 MVVM 框架,代码实现可能也比较粗糙,但是通过造这个轮子还是增长了很多知识的 ~ 进步在于折腾嘛!
目前我的 mvvm.js 只是实现了最本的功能,以后我会继续完善、健壮它,如有兴趣欢迎一起探讨和改进~