Skip to content

Instantly share code, notes, and snippets.

@amowu
Created October 5, 2016 04:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save amowu/6540183ac6e323b9cb44bcb104fedbde to your computer and use it in GitHub Desktop.
Save amowu/6540183ac6e323b9cb44bcb104fedbde to your computer and use it in GitHub Desktop.
How to Implement DOM Data Binding in Pure JavaScript
// http://stackoverflow.com/a/16484266/754377
function DataBind(element, data) {
this.data = data;
this.element = element;
element.value = data;
element.addEventListener("change", this, false);
}
DataBind.prototype.handleEvent = function(event) {
switch (event.type) {
case "change": this.change(this.element.value);
}
};
DataBind.prototype.change = function(value) {
this.data = value;
this.element.value = value;
};
var obj = new DataBind(document.getElementById("foo"), "initial");
// simulate some JS based changes.
var i = 0;
setInterval(function() {
obj.change(obj.element.value + ++i);
}, 3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment