今天突发奇想的极简双向数据绑定
今天面试nodejs被双向数据绑定考蒙了,感觉智商收到了严重的侮辱,特写一个极单的双向绑定安慰下自己
class Bind {
constructor(type, element) {
this.type = type;
this.element = element;
}
get prop() {
if (this.type === 'html') {
return this.element.innerHTML;
} else if (this.type === 'value') {
return this.element.value
}
}
set prop(value) {
if (this.type === 'html') {
this.element.innerHTML = value;
} else if (this.type === 'value') {
this.element.value = value;
}
}
}
class Data {
constructor(data) {
this.data = data;
this.map = new Map();
const doms = document.querySelectorAll("body *");
for (const dom of doms) {
let prop;
let bind;
if (dom.dataset.html) {
prop = dom.dataset.html;
bind = new Bind('html', dom);
} else if (dom.dataset.value) {
prop = dom.dataset.value;
bind = new Bind('value', dom);
}
if (prop) {
this.map.set(`${prop}`, bind);
}
}
}
change(prop, value) {
const bind = this.map.get(prop);
bind.prop = value;
this.map.set(prop, bind);
}
}
const bind = (data) => {
const databind = new Data(data);
const proxy=new Proxy(data,{
set(target,key,value){
databind.change(key, value);
}
})
return proxy;
}
测试页:
<html>
<head>
<script src="./bind.js"></script>
</head>
<body>
<div data-html='a'></div>
<input type='text' data-value='b'>
<script>
var data = {
a: '',
b: ''
};
data=bind(data);
setInterval(() => {
data.a = +new Date();
data.b = +new Date();
}, 1000);
</script>
</body>
</html>
2 回复
前排水果瓜子
这是Vue的方法。
其实脏检查也可以的 :)