Skip to content

Instantly share code, notes, and snippets.

@zbabtkis
Created January 4, 2014 00:58
Show Gist options
  • Save zbabtkis/8249985 to your computer and use it in GitHub Desktop.
Save zbabtkis/8249985 to your computer and use it in GitHub Desktop.
Tiny JavaScript data-binder using Object.observe.
var DataBind = function(el, model) {
this.el = el;
this.model = model;
// Bind event handlers to this.
this._updateModel = this._updateModel.bind(this);
this._updateEl = this._updateEl.bind(this);
Object.observe(model, this._updateEl);
this.el.addEventListener('keyup', this._updateModel, false);
};
// Update element value when model attribute changes.
DataBind.prototype._updateEl = function(change) {
var val, name;
for(var i = 0; i < change.length; i++) {
name = change[i].name;
if(this.el.dataset.bind === name) {
val = change[i].object[name];
this.el.value = val;
this.el.innerHTML = val;
}
}
};
// Update model when element value changes.
DataBind.prototype._updateModel = function(change) {
var attr = change.target.dataset.bind;
this.model[attr] = change.target.value;
};
// Destroy current data binding.
DataBind.prototype.destroy = function() {
this.el.removeEventListener('keyup', this._updateModel, false);
Object.unobserve(this.model, this._updateEl);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment