Created
May 10, 2020 19:52
-
-
Save nitish24p/727e3b4b26c811ab1c6c4ace0cbbc263 to your computer and use it in GitHub Desktop.
TwoWayBinding.js
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
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