// 实现数据改变,视图同步功能
class Dep { // 存储订阅者
constructor() {}
}
class Observer { // 数据代理
constructor(data) {
this.analysisData(data);
this.dep = new Dep();
}
analysisData(data) {
if (Object.prototype.toString.call(data) === '[object Object]') {
Object.keys(data).forEach(key => {
let value = data[key];
this.analysisData(value);
let node = undefined;
Object.defineProperty(data, key, {
enumerable: true,
configurable: true,
get: () => {
if (Dep.node) {
node = Dep.node;
}
return value
},
set: (newValue) => {
value = newValue;
if (node) {
node.textContent = newValue;
}
return value;
}
})
})
}
}
}
class Compile { // 数据和dom绑定
constructor(data, id) {
this.root = document.querySelector(id);
this.reg = /\{\{(.*)\}\}/;
this.data = data;
this.compile(this.root, this.reg);
}
compile(root, reg) {
let childNodes = root.childNodes;
[...childNodes].forEach((node) => {
let text = node.textContent;
if (node.nodeType === 3 && reg.test(text)) {
let key = reg.exec(text)[1];
Dep.node = node;
node.textContent = this.data[key];
Dep.node = undefined;
}
if (node.childNodes && node.childNodes.length > 0) {
this.compile(node, reg)
}
})
}
}
class MyVue {
constructor({
el,
data
}) {
new Observer(data);
new Compile(data, el)
}
}
const data = {
name: '小明'
};
new MyVue({
el: '#root',
data
})
setTimeout(() => {
data.name = '小红'
}, 1000)
03-30
1750
09-29