bilibiliQQ
2023-11-25 17:17:13 +08:00
30 行 JS 代码搞定前端双向数据绑定,最简版本:
let data = new Proxy({}, {
set(obj, key, value) {
obj[key] = value;
const dataElements = document.querySelectorAll(`[bind-data="${key}"]`);
const funcElements = document.querySelectorAll("[bind-fun]");
dataElements.forEach((element) => {
element instanceof HTMLInputElement ? (element.value = value) : (element.innerText = value);
});
if (funcElements.length > 0) {
funcElements.forEach((element) => {
const funcName = element.getAttribute("bind-fun");
if (typeof window[funcName] !== "function") return;
const func = window[funcName].bind(obj);
const val = func() || "";
element instanceof HTMLInputElement ? (element.value = val) : (element.innerText = val);
});
}
return true;
},
get(obj, key) {
return obj[key];
},
});
document.addEventListener("input", function (event) {
if (!event.target.hasAttribute("bind-data")) return;
data[event.target.getAttribute("bind-data")] = event.target.value;
});