Skip to content

Instantly share code, notes, and snippets.

@jremi
Last active March 29, 2021 05:54
Show Gist options
  • Save jremi/13a1c2d688e37f8f640d6c3273655988 to your computer and use it in GitHub Desktop.
Save jremi/13a1c2d688e37f8f640d6c3273655988 to your computer and use it in GitHub Desktop.
Simple Two Way Binding Using JS Proxy and DOM inputs
/*
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