Bind an object property to an input both ways, without a framework
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 directionsRef. UR-1420 · © UIRound · uiround.com/questions/bind-an-object-property-to-an-input-both-ways-without-a-framework
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 2
- code listings
- 5
- edge cases
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1Two directions need two mechanisms. Input to state is an event listener. State to input needs to notice a plain assignment like state.name = 'Ravi', which only a setter can do.
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.