Skip to content

Instantly share code, notes, and snippets.

@kevin-bruton
Last active February 23, 2020 19:36
Show Gist options
  • Save kevin-bruton/2b498a5011db71512716ea00ac9ee9b3 to your computer and use it in GitHub Desktop.
Save kevin-bruton/2b498a5011db71512716ea00ac9ee9b3 to your computer and use it in GitHub Desktop.
One way binding in native javascript
// data binding in native javascript:
// https://stackblitz.com/edit/databinding-native-js
// Example html:
// <span id="labelEl">default</span>: <span id="nameEl">default</span>
const setupBindings = bindings =>
bindings.reduce((acc, cur) =>
Object.defineProperty(acc, cur.bindingName, {
set: val => (cur.element[cur.attribute] = val)
}), {});
const binding = setupBindings([
{element: document.getElementById("labelEl"), attribute: 'innerHTML', bindingName: 'nameLabel'},
{element: document.getElementById("nameEl"), attribute: 'innerHTML', bindingName: 'nameValue'},
{element: document.getElementById("nameEl"), attribute: 'hidden', bindingName: 'nameIsHidden'}
]);
// Example of usage:
// binding.nameLabel = "Name";
// binding.nameValue = "Kevin"
// binding.nameIsHidden = true;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment