Last active
February 23, 2020 19:36
-
-
Save kevin-bruton/2b498a5011db71512716ea00ac9ee9b3 to your computer and use it in GitHub Desktop.
One way binding in native javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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