Skip to curriculum
Jump to the editor

18.3. Two-way binding between an input and an object

Medium
Topics
20–30 min

A settings form and a settings object should agree. When the user types, the object should change; when code changes the object (a reset button, data from the server), the field should show it. Frameworks do this for you; underneath, it takes one listener for each direction and a way to notice when a property is assigned.

Write bind(input, model, key) in bind.js. It keeps model[key] and a form control in sync in both directions, and returns an unbind function.

Signature

JAVASCRIPT
function bind(input, model, key) // returns unbind()
  • input: a text-like <input>, a <textarea>, or an <input type="checkbox">.
  • model: a plain object. key: the property name to bind.
  • unbind(): stops syncing and leaves model[key] as an ordinary property holding the last value.

Requirements

  1. At the start, the control shows model[key]: null and undefined show as an empty field, other values through String().
  2. If the model has no own property key, it takes the control's current value instead (the control is not changed).
  3. Typing (an input event on the control) updates model[key] to the control's string value.
  4. Assigning model[key] = x updates the control, and reading model[key] returns x exactly as assigned.
  5. Assigning fires no input event and never loops.
  6. model[key] stays enumerable: Object.keys and JSON.stringify see it, with the current value. Other properties are untouched.
  7. A checkbox syncs checked (a boolean) on change events; assigning sets checked to Boolean(x).
  8. Only events on the bound control count.
  9. Each binding is independent: two keys of one model can be bound to two controls.
  10. unbind() removes the listener and turns model[key] back into a plain writable, enumerable, configurable data property with the last value. Calling it again does nothing; it never removes other listeners.
  11. Binding a key that is already an accessor property (bound already, or defined with get and set, even when both are undefined) throws TypeError, and so does a frozen model. A failed bind changes neither the control nor the model.

Examples

JAVASCRIPT
const model = { name: "Ada" };
const unbind = bind(document.querySelector("#name"), model, "name");
// the field shows "Ada"
// the user types "Grace"
model.name;            // "Grace"
model.name = "Reset";  // the field shows "Reset"
JSON.stringify(model); // '{"name":"Reset"}'
JAVASCRIPT
const prefs = { news: true };
bind(document.querySelector("#news"), prefs, "news"); // the box is checked
// the user clicks it
prefs.news;            // false
JAVASCRIPT
const draft = {};
bind(textarea, draft, "body"); // the textarea already holds "hello"
draft.body;            // "hello"
unbind();
Object.getOwnPropertyDescriptor(model, "name");
// { value: "Reset", writable: true, enumerable: true, configurable: true }

Environment

  • Plain JavaScript in a browser page; the tests call the global bind from bind.js with controls they create.
  • The tests simulate typing by setting value and dispatching an input event, and click checkboxes with click().
  • Out of scope: radio groups, <select multiple>, number conversion, binding one key to two controls, and nested keys like "address.city".

Hints

  1. A plain property cannot tell you it was assigned. What kind of property runs your code on every assignment?
  2. If the getter reads model[key], what happens?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…