Skip to content

Instantly share code, notes, and snippets.

@nitish24p
Created May 10, 2020 19:52
Show Gist options
  • Save nitish24p/727e3b4b26c811ab1c6c4ace0cbbc263 to your computer and use it in GitHub Desktop.
Save nitish24p/727e3b4b26c811ab1c6c4ace0cbbc263 to your computer and use it in GitHub Desktop.
TwoWayBinding.js
const Binding = (function () {
function initialise(appNode, callback) {
const model = {};
const nodes = appNode.querySelectorAll('[data-bind]');
/** ============== Two way bind =============== */
nodes.forEach(function (element) {
const key = element.getAttribute('data-bind');
hookElementToModel(key);
if (element.type === 'text' || element.type === 'textarea') {
element.addEventListener('keyup', function () {
model[key] = this.value;
});
}
});
function hookElementToModel(key) {
if (!model.hasOwnProperty(key)) {
let value;
Object.defineProperty(model, key, {
enumerable: true,
set: function (newValue) {
value = newValue;
nodes.forEach((element) => {
if (element.getAttribute('data-bind') === key) {
if (
element.type &&
(element.type === 'text' || element.type === 'textarea')
) {
element.value = newValue;
} else if (!element.type) {
element.innerHTML = newValue;
}
}
});
},
get: function () {
return value;
},
});
}
}
/** ============== Two way bind End =============== */
return {
initialise,
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment