virtual dom & mvvm
虚拟dom
- 用js对象来表示dom树的结构,然后用这个对象来构建一个真正的dom树插入文档中;
- 当状态有变时,重新构造一个新的对象树,然后比较新的和旧的树,记录两个数的差异;
- 把差异部分应用到真正的dom树上,更新视图。
核心算法实现(diff算法)
- 用js对象表示dom树
var e = {
tagName: 'ul',
props: {
id: 'list'
},
children: [
{tagName: 'li', props: {class: 'li1'}, children: ['item1']},
{tagName: 'li', props: {class: 'li2'}, children: ['item2']},
{tagName: 'li', props: {class: 'li3'}, children: [
{tagName: 'h2', props: {class: 'h'}, children: ['hello qq']}
]},
]
} - 把js对象渲染成dom树
function dom(tagName, props, children){
function Element(tagName, props, children){
this.tagName = tagName;
this.props = props;
this.children = children;
}
Element.prototype.render = function(){
const el = document.createElement(this.tagName);
const props = this.props;
for(let key in props){
el.setAttribute(key, props[key]);
}
const children = this.children || [];
children.forEach(child => {
const c = child.tagName ? new Element(child.tagName, child.props, child.children).render() : document.createTextNode(child);
el.appendChild(c);
})
return el;
}
return new Element(tagName, props, children);
} - 比较两个虚拟dom树的差异,同层节点进行比较(时间复杂度O(n));
对每一个树在深度优先遍历的时候,每遍历到一个节点就把该节点和新的的树进行对比,把差异部分记录到一个对象里面。// diff 函数,对比两棵树
function diff (oldTree, newTree) {
var index = 0 // 当前节点的标志
var patches = {} // 用来记录每个节点差异的对象
dfsWalk(oldTree, newTree, index, patches)
return patches
} // 对两棵树进行深度优先遍历
function dfsWalk (oldNode, newNode, index, patches) {
// 对比oldNode和newNode的不同,记录下来
patches[index] = [...] diffChildren(oldNode.children, newNode.children, index, patches)
} // 遍历子节点
function diffChildren (oldChildren, newChildren, index, patches) {
var leftNode = null
var currentNodeIndex = index
oldChildren.forEach(function (child, i) {
var newChild = newChildren[i]
currentNodeIndex = (leftNode && leftNode.count) // 计算节点的标识
? currentNodeIndex + leftNode.count + 1
: currentNodeIndex + 1
dfsWalk(child, newChild, currentNodeIndex, patches) // 深度遍历子节点
leftNode = child
})
} - 因为步骤一所构建的 JavaScript 对象树和render出来真正的DOM树的信息、结构是一样的。所以我们可以对那棵DOM树也进行深度优先的遍历,遍历的时候从步骤二生成的paches对象中找出当前遍历的节点差异,然后进行 DOM 操作。
function patch (node, patches) {
var walker = {index: 0}
dfsWalk(node, walker, patches)
} function dfsWalk (node, walker, patches) {
var currentPatches = patches[walker.index] // 从patches拿出当前节点的差异 var len = node.childNodes
? node.childNodes.length
: 0
for (var i = 0; i < len; i++) { // 深度遍历子节点
var child = node.childNodes[i]
walker.index++
dfsWalk(child, walker, patches)
} if (currentPatches) {
applyPatches(node, currentPatches) // 对当前节点进行DOM操作
}
} function applyPatches (node, currentPatches) {
currentPatches.forEach(function (currentPatch) {
switch (currentPatch.type) {
case REPLACE:
node.parentNode.replaceChild(currentPatch.node.render(), node)
break
case REORDER:
reorderChildren(node, currentPatch.moves)
break
case PROPS:
setProps(node, currentPatch.props)
break
case TEXT:
node.textContent = currentPatch.content
break
default:
throw new Error('Unknown patch type ' + currentPatch.type)
}
})
}
Vue之MVVM简单实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>MVVM</title>
</head>
<body>
<div id='app'>
<h2>{{ song }}</h2>
<h3>{{ obj.name }}</h3>
<h3>{{ obj.a }}</h3>
<h3>{{ obj.obj1.name1 }}</h3>
<input type="text" v-model='msg'>
<h3>{{ msg }}</h3>
<h2>{{ total }}</h2>
</div>
<script src="index.js"></script>
<script>
let vm = new Vm({
el: '#app',
data(){
return {
song: 'Time',
obj: {
name: 'xxx',
a: 20,
b: 3,
obj1: {
name1: 'll'
}
},
msg: 'hello'
}
},
computed: {
total() {
return this.obj.a * this.obj.b;
}
},
mounted() {
console.log(this.$el)
console.log('everything is done')
}
})
</script>
</body>
</html>
function Vm(opts = {}){
this.$opts = opts;
let data = this.$data = this.$opts.data();
initComputed.call(this);
// 数据监测
observer(data);
for (let key in data) {
Object.defineProperty(this, key, {
configurable: true,
get() {
return this.$data[key];
},
set(newVal) {
this.$data[key] = newVal;
}
});
}
// 数据编译
new Compile(opts.el, this);
opts.mounted.call(this);
}
function initComputed(){
let vm = this;
let computed = this.$opts.computed;
Object.keys(computed).forEach(key => {
Object.defineProperty(vm, key, {
get: typeof computed[key] === 'function' ? computed[key] : computed[key].get,
set(){}
})
})
}
function observer(data) {
if(!data || typeof data !== 'object') return;
return new Observer(data);
}
function Observer(data) {
let dep = new Dep();
for (let key in data) {
let val = data[key];
observer(val);
Object.defineProperty(data, key, {
configurable: true,
get() {
Dep.target && dep.addSub(Dep.target);
return val;
},
set(newVal) {
if(val === newVal) return;
val = newVal;
observer(newVal);
dep.notify();
}
})
}
}
function Compile(el, vm){
vm.$el = document.querySelector(el);
var fragment = document.createDocumentFragment();
var child;
while(child = vm.$el.firstChild) {
fragment.appendChild(child);
}
function replace(fragment){
Array.from(fragment.childNodes).forEach(item => {
let text = item.textContent;
let reg = /\{\{(.*?)\}\}/g;
if(item.nodeType === 3 && reg.test(text)){
// 重点重点重点!!!!!!
// 去掉空格!!!!!!!!
function replaceTxt() {
item.textContent = text.replace(reg, (matched, placeholder) => {
console.log(placeholder); // 匹配到的分组 如:song, album.name, singer...
new Watcher(vm, placeholder.trim(), replaceTxt); // 监听变化,进行匹配替换内容
return placeholder.trim().split('.').reduce((val, key) => {
return val[key];
}, vm);
});
};
replaceTxt();
}
if(item.nodeType === 1){
let itemAttr = item.attributes;
Array.from(itemAttr).forEach(attr => {
let name = attr.name;
let exp = attr.value;
if(name.includes('v-')){
item.value = vm[exp];
}
new Watcher(vm, exp, newVal => {
item.value = newVal;
})
item.addEventListener('input', e => {
vm[exp] = e.target.value;
})
})
}
if(item.childNodes && item.childNodes.length){
replace(item);
}
})
}
replace(fragment);
vm.$el.appendChild(fragment);
}
// 发布订阅
function Dep(){
this.subs = [];
}
Dep.prototype = {
addSub(sub){
this.subs.push(sub);
},
notify(){
this.subs.forEach(sub => {
sub.update()
});
}
}
function Watcher(vm, exp, fn){
this.fn = fn;
this.vm = vm;
this.exp = exp;
Dep.target = this;
let arr = exp.split('.');
let val = vm;
arr.forEach(key => {
val = val[key];
});
Dep.target = null;
}
Watcher.prototype.update = function(){
let arr = this.exp.split('.');
let val = this.vm;
arr.forEach(key => {
val = val[key]; // 通过get获取到新的值
});
this.fn(val);
}
// let watcher = new Watcher(() => {
// console.log('watch')
// })
// let dep = new Dep();
// dep.addSub(watcher);
// dep.addSub(watcher);
// dep.notify();
virtual dom & mvvm的更多相关文章
- 个人对于Virtual DOM的一些理解
之前一直认为react的Virtual DOM操作会比传统的操作DOM要快,这其实是错误的,React 从来没有说过 "React 比原生操作 DOM 快".如果没有 Virtua ...
- 抛开react,如何理解virtual dom和immutability
去年以来,React的出现为前端框架设计和编程模式吹来了一阵春风.很多概念,无论是原本已有的.还是由React首先提出的,都因为React的流行而倍受关注,成为大家研究和学习的热点.本篇分享主要就聚焦 ...
- 深度剖析:如何实现一个 Virtual DOM 算法
本文转载自:https://github.com/livoras/blog/issues/13 目录: 1 前言 2 对前端应用状态管理思考 3 Virtual DOM 算法 4 算法实现 4.1 步 ...
- Virtual DOM 算法
前端 virtual-dom react.js javascript 目录: 1 前言 2 对前端应用状态管理思考 3 Virtual DOM 算法 4 算法实现 4.1 步骤一:用JS对象模拟DOM ...
- virtual dom的实践
最近基于virtual dom 写了一个小框架-aoy. aoy是一个轻量级的mvvm框架,基于Virtual DOM.虽然现在看起来很单薄,但我做了完善的单元测试,可以放心使用.aoy的原理可以说和 ...
- 深度理解 Virtual DOM
目录: 1 前言 2 技术发展史 3 Virtual DOM 算法 4 Virtual DOM 实现 5 Virtual DOM 树的差异(Diff算法) 6 结语 7 参考链接 1 前言 我会尽量把 ...
- Virtual DOM 系列一:认识虚拟DOM
1. 什么是Virtual DOM? Virtual DOM(虚拟DOM)是指用JS模拟DOM结构.本质上来讲VD是一个JS对象,并且至少包含三个属性:tag(html标签),props(标签的属性, ...
- 实现一个 Virtual DOM 算法
1 前言 本文会在教你怎么用 300~400 行代码实现一个基本的 Virtual DOM 算法,并且尝试尽量把 Virtual DOM 的算法思路阐述清楚.希望在阅读本文后,能让你深入理解 Virt ...
- Virtual DOM 虚拟DOM的理解(转)
作者:戴嘉华 转载请注明出处并保留原文链接( #13 )和作者信息. 目录: 1 前言 2 对前端应用状态管理思考 3 Virtual DOM 算法 4 算法实现 4.1 步骤一:用JS对象模拟DOM ...
随机推荐
- Linux ssh服务
关于ssh服务不多说就提几句,1,机房的服务器一般都是通过远程连接登录的,远程登录就必然少不了ssh客户端.2,虚拟机每次都要点击进去,每次退出来也需要按Ctrl+Alt+Enter,也比较麻烦,有时 ...
- My Neural Network isn't working! What should I do?
参考文献:http://theorangeduck.com/page/neural-network-not-working 我的网络不起作用!该怎么办? 因此,你在深度学习方面正在开发下一个重大突破, ...
- usb-tooltip 重写.tooltip { word-break: break-all; }解决单词内换行
<div style="padding: 5px 10px; font-size: 16px; text-align: left" class="truncate& ...
- macOS Sierra上ssh免密码登录linux服务器
1.生成私钥文件 在客户端终端下输入以下命令 ssh-keygen -t rsa 每次执行 ssh-keygen -t rsa 产生的私钥文件都会不同 如果文件"~/.ssh/id_rsa& ...
- Python(线程进程2)
新进程的创建都是由一个已经存在的进程执行了一个用于创建进程的系统调用而创建的: 1. 在UNIX中该系统调用是:fork,fork会创建一个与父进程一模一样的副本,二者有相同的存储映像.同样的环境字符 ...
- MyBatisPartA
(正在补充) 1.从第一个程序开始,通过mybatis实现数据库表内容的增删改查 (源码zip包) 1.0准备工作 建数据库mybatis,在其中创建表sql语句如下: ; -- ---------- ...
- cocostudio 在VS模拟器中加载资源显示混乱问题
这个是由于cocos2d-x的资源是统一按照文件名管理的,所以游戏全局不能有重名. PS:所有用到的素材名字必须单一.
- Apple 的命令行交付工具“Transporter”
Apple 的命令行交付工具“Transporter” 占坑... https://help.apple.com/itc/transporteruserguide/#/apdATD1E1026-D1E ...
- Python面试题目之(针对dict或者set数据类型)边遍历 边修改 报错dictionary changed size during iteration
# result 是一个字典, 把里面属性值是None的属性删除 for key in result: if not result[key]: del result[key] continue 但是报 ...
- Web安全学习笔记之Nmap脚本编写
0x00 Nmap脚本简介 夜无眠,看了一下Nmap官方的英文API文档(全是English),瞬间心态崩塌,不想吐槽它们的nmap官网前端太丑了=.=,但是都是大牛啊,挺敬佩开源开发者的. Nmap ...