Bind an object property to an input both ways, without a framework

easyAbout 25 minutesUpdated CodingProdomeventstwo-way-bindinggetters-setters
Not solved

Share this question

Problem

Vue's v-model and Angular's [(ngModel)] keep a piece of state and a form field in sync in both directions. Build the core of it in plain JavaScript: bindInput(state, key, input), which ties state[key] to an <input> element and returns an unbind() function.

const state = { name: "Asha" };
const input = document.querySelector("#name");

const unbind = bindInput(state, "name", input);
input.value;          // "Asha"   (state → input on bind)

state.name = "Ravi";
input.value;          // "Ravi"   (state → input on assignment)

// the user types "Meera"
state.name;           // "Meera"  (input → state on every keystroke)

unbind();             // stops syncing in both directions

Ref. UR-1420 · © UIRound · uiround.com/questions/bind-an-object-property-to-an-input-both-ways-without-a-framework

Stuck? Take a hint

Try it in the editor

Run your code as often as you like. Submitting it to the full test suite is part of Pro.

Private, and saved in this browser as you type. All your notes are on My lists.

Every question and answer7 days, one payment