Today I Learned - Rocky Kev

TIL How to implement two-way binding without a framework

POSTED ON:

TAGS:

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:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.