尝试 javascript 一对多 双向绑定器
<!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>