Last active
September 8, 2018 07:29
-
-
Save GeorgianStan/25448275091a812afe978fedf9084c95 to your computer and use it in GitHub Desktop.
2-Way-DataBinding-JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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; | |
} | |
}) | |
} | |
}) | |
} | |
}; | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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