Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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