Native two way data binding
Simple demonstration of two way data binding using vanilla js.
by Brenton Strine
HTML
<input type="text" value="" class="js-form js-data1">
<p>
The form above says <code class="js-code js-data1" contentEditable="true"></code>!
</p>
JavaScript
var myApp = {};
myApp.data = {
data1: null,
}
for(prop in myApp.data) {
if(myApp.data.hasOwnProperty(prop)){
var selector = ".js-" + prop;
document
.querySelectorAll(selector)
.forEach(function(elem){
elem.addEventListener("keyup", function(){
var value = this.value || this.textContent;
myApp.updateValues(prop, value);
});
});
}
}
myApp.updateValues = function(property, value) {
myApp.data[property] = value;
document
.querySelectorAll(".js-"+property)
.forEach(function(elem){
if (elem.tagName.toUpperCase() === "INPUT") {
elem.value = myApp.data[property];
} else {
elem.textContent = myApp.data[property];
}
});
}
window.myApp = myApp;
myApp.updateValues("data1", "~~change me~~");