尝试 javascript 一对多 双向绑定器
程序员文章站
2022-03-07 10:32:42
<!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>document</title>
</head>
<body>
<h1 class="disp"></h1>
<h2 class="disp"></h2>
<h3 id="d3" class='disp'></h3>
<input type="text" id="inp1"></input>
<input type="text" id='inp2'></input>
<input type="text" id='inp3'></input>
<script>
var man = { name: 'zhang' , age: 1 };
function bind(obj, key, selector, prop, event = undefined) {
debugger
var els = document.queryselectorall(selector);
var value_1 = obj[key];
array.prototype.slice.call(els).foreach(function (el) {
if (event) { el.addeventlistener(event, function () { obj[key] = el[prop]; }) }
if (!obj.__ep__) obj.__ep__ = {};
object.defineproperty(obj, "__ep__", { enumerable: true });
if (!obj.__ep__[key]) {
obj.__ep__[key] = [];
obj.__ep__[key].push({ el: el, prop: prop });
object.defineproperty(obj, key, {
get: function () { return obj.__ep__[key].value },
set: function (value) {
obj.__ep__[key].value = value;
obj.__ep__[key].foreach(ep => { ep.el[ep.prop] = value });
}
})
} else { obj.__ep__[key].push({ el: el, prop: prop }); }
object.defineproperty(obj, "__ep__", { enumerable: false });
})
obj[key] = value_1;
}
bind(man, 'name', '#inp1', 'value', 'input');
bind(man, 'name', '#inp2', 'value', 'change');
bind(man, 'name', '.disp', 'innerhtml');
bind(man,'age','#inp3','value','input')
bind(man,'age','#d3','innerhtml')
//document.body.removechild(document.queryselector('#inp1'))
</script>
</body>
</html>
上一篇: vue项目实现左滑删除功能(完整代码)
下一篇: STM8L独立看门狗IWDG