Skip to content

Instantly share code, notes, and snippets.

@harish81
Last active June 5, 2023 22:32
Show Gist options
  • Save harish81/ee6ec876ae28750f8e2ecba57b9aa2ec to your computer and use it in GitHub Desktop.
Save harish81/ee6ec876ae28750f8e2ecba57b9aa2ec to your computer and use it in GitHub Desktop.
Simple Two-Way Data Binding Using Javascript Proxies.
function observe(selector,data,listener=null) {
let parent = document.querySelector(selector);
let allBind = parent.querySelectorAll('[data-bind]');
const get = (target, key, receiver)=>{
const result = Reflect.get(target, key, receiver);
return result;
}
const set = (target,key,value,receiver)=>{
Reflect.set(target, key, value, receiver);
updateBinding(key,value);
}
const updateBinding = (key,value)=>{
parent.querySelector('[data-bind="'+key+'"]').value = value;
parent.querySelectorAll('[data-text="'+key+'"]').forEach(elem=>{elem.textContent=value});
if(listener)
listener(key,value);
}
const changeEvent = (e)=>{
let target = e.target;
let bindAttr = target.getAttribute("data-bind");
proxy[bindAttr] = target.value;
}
allBind.forEach((item,index)=>{
item.addEventListener('input', changeEvent);
});
for(let itemKey in data){
updateBinding(itemKey, data[itemKey]);
}
let proxy = new Proxy(data,{get, set});
return proxy;
}
<!DOCTYPE html>
<html>
<head>
<title>Two Way Binding Using Proxies</title>
<style type="text/css">
span[data-text]{
font-weight: bold;
}
</style>
</head>
<body>
<h1>Two way binding using proxies</h1>
<div id="myform">
<input type="text" name="name" data-bind="name" autocomplete="off">
<input type="number" name="age" data-bind="age">
<select data-bind="grade">
<option>One</option>
<option>Two</option>
</select>
<br>
<br>
<div>
Hi, Mr. <span data-text="name"></span>. Your age is <span data-text="age"></span>, Grade=> <span data-text="grade"></span>
</div>
</div>
<br><br>
<button>Save</button>
<script type="text/javascript" src="binding.js"></script>
<script type="text/javascript">
var myform = observe("#myform",{name:'John',age:0,grade:'Two'},function(key,value){
console.log(key+"="+value);
console.log(myform);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment