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.
At the start, the control shows model[key]: null and undefined show as an empty field, other values through String().
If the model has no own property key, it takes the control's current value instead (the control is not changed).
Typing (an input event on the control) updates model[key] to the control's string value.
Assigning model[key] = x updates the control, and reading model[key] returns x exactly as assigned.
Assigning fires no input event and never loops.
model[key] stays enumerable: Object.keys and JSON.stringify see it, with the current value. Other properties are untouched.
A checkbox syncs checked (a boolean) on change events; assigning sets checked to Boolean(x).
Only events on the bound control count.
Each binding is independent: two keys of one model can be bound to two controls.
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.
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.
constmodel= { name: "Ada" };constunbind=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
constprefs= { news: true };bind(document.querySelector("#news"), prefs, "news"); // the box is checked// the user clicks itprefs.news; // false