TIL How to implement two-way binding without a framework
POSTED ON:
TAGS: javascript vue codepen react data
One of the reasons we use React or Vue is because of that sweet sweet two-way binding.
It's the automatic syncing of data between the model (data) and the view (UI) in both directions. Any changes made to the data will automatically update the view, and any changes made to the view will automatically update the data.
How to do it without a framework:
See the Pen Untitled by rockykev (@rockykev) on CodePen.
<input id="inputEl" placeholder="Enter a number..." type="text" />
<span id="val"></span>
<button id="incrementVal">Increment</button>
<script>
const data = {
value: ''
};
const el = document.getElementById('inputEl');
Object.defineProperty(data, 'prop', {
get: function() {
console.log('Getter called');
return this.value;
},
set: function(value) {
console.log('Setter called');
this.value = value;
el.value = value;
printVal();
}
});
function printVal() {
const el = document.getElementById('val');
el.innerText = data.prop;
}
// attaching the event listener on keyup events
el.addEventListener('keyup', (event) => {
data.prop = event.target.value;
});
const btn = document.getElementById('incrementVal');
btn.addEventListener('click', () => {
data.prop = Number(data.prop) + 1;
});
</script>
via Two-way data binding in Vanilla JavaScript without Angular or React
Related TILs
Tagged: javascript