运行截图
本文能做的
- 带你了解一下
Proxy
的使用
- 了解通过插值表达式怎么实现简易版的数据驱动
- 代码仅是简单Demo,参考了50行代码的MVVM,感受闭包的艺术,一篇好文章,因为时间,沉底了,掏出来再学习一下~
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>pVue-proxy-mvvm</title>
</head>
<body>
<div id="app">
<p>hello, {{ name }}</p>
<div>
<span>author: {{ author }}</span>
<span style="margin-left: 24px">time: {{ time }}</span>
</div>
</div>
<script>
document.addEventListener("DOMContentLoaded", () => {
const vm = new pVue({
el: "#app",
data: {
name: "Proxy",
time: new Date(),
author: "arley",
},
})
for (let i = 0; i < 10; i++) {
setTimeout(() => {
this.data.name = `pVue, update: ${i}`
}, 200 * (i + 1))
}
})
class pVue {
constructor(options) {
const { el, data } = options
this.options = options
this._nodes = {}
window.data = this.onProxy(data)
this.render(document.querySelector(el))
}
onProxy(data) {
const that = this
const handler = {
set(target, property, value, receiver) {
that._nodes[property].node.innerHTML = that._nodes[property].defaultData.replace(
new RegExp(`{{\\s*${property}\\s*}}`, "g"),
value
)
return Reflect.set(target, property, value)
},
}
return new Proxy(data, handler)
}
render(node) {
Array.prototype.forEach.call(node.childNodes, (child) => {
if (
!child.firstElementChild &&
/\{\{(.+?)\}\}/.test(child.innerHTML)
) {
const key = RegExp.$1.trim()
this._nodes[key] = {
node: child,
defaultData: child.innerHTML
}
child.innerHTML = child.innerHTML.replace(
new RegExp(`{{\\s*${key}\\s*}}`, "g"),
this.options.data[key]
)
} else if (child.firstElementChild) {
this.render(child)
}
})
}
}
</script>
</body>
</html>