Skip to content

Instantly share code, notes, and snippets.

@GeorgianStan
Last active September 8, 2018 07:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GeorgianStan/25448275091a812afe978fedf9084c95 to your computer and use it in GitHub Desktop.
Save GeorgianStan/25448275091a812afe978fedf9084c95 to your computer and use it in GitHub Desktop.
2-Way-DataBinding-JS
"use strict";
let scope = {};
(function twoWayDataBinding() {
let bindingItems = document.querySelectorAll('[tw-binding]');
// loop through all bindable elements
bindingItems.forEach((e) => {
if (e.type == "text") {
let propToBind = e.getAttribute("tw-binding");
addScope(propToBind);
e.onkeyup = function () {
scope[propToBind] = e.value;
}
}
});
// add to scope object new property if needed
function addScope(propToBind){
if(!scope.hasOwnProperty(propToBind)){
let value;
Object.defineProperty(scope, propToBind, {
get() { return value;},
set(newValue){
value = newValue;
bindingItems.forEach( (item) => {
if( item.getAttribute("tw-binding") == propToBind){
if(item.type === "text"){
item.value = newValue
} else if(!item.type) item.innerHTML = newValue;
}
})
}
})
}
};
})();
<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>
Name: <input tw-binding="name" type="text">
<input tw-binding="name" type="text">
<hr />
Age: <input tw-binding="age" type="text">
<input tw-binding="age" type="text">
<p tw-binding="age"></p>
<!-- Script -->
<script src="index.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment