Last active
March 29, 2021 05:54
-
-
Save jremi/13a1c2d688e37f8f640d6c3273655988 to your computer and use it in GitHub Desktop.
Simple Two Way Binding Using JS Proxy and DOM inputs
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
/* | |
Example HTML: | |
Name: <input v-model="name" /> | |
Age: <input v-model="age" /> | |
Color: <input v-model="color" /> | |
*/ | |
/* | |
Usage: | |
Whenever you set the variable for example: | |
data.name = 'Bob'; | |
The input field will automatically update. | |
Whenever you change the value of the input text field | |
the variable will automatically update. | |
The v-model="" is where you specifiy the variable property to bind | |
to the object. The v-model is inspired by Vue :) | |
This is just a contrived test example. | |
*/ | |
const findModelEl = (modelName) => { | |
return document.querySelector(`[v-model="${modelName}"]`); | |
}; | |
const data = new Proxy( | |
{}, | |
{ | |
set: (obj, prop, value) => { | |
obj[prop] = value; | |
findModelEl(prop).value = value; | |
return true; | |
}, | |
} | |
); | |
document.querySelectorAll("[v-model]").forEach((vModelEl) => { | |
vModelEl.oninput = (event) => | |
(data[vModelEl.attributes[0].value] = event.target.value); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment