Skip to content

Instantly share code, notes, and snippets.

@zbabtkis
Created January 4, 2014 00:58
Show Gist options
  • Select an option

  • Save zbabtkis/8249985 to your computer and use it in GitHub Desktop.

Select an option

Save zbabtkis/8249985 to your computer and use it in GitHub Desktop.

Revisions

  1. Zachary Babtkis created this gist Jan 4, 2014.
    38 changes: 38 additions & 0 deletions DataBind.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    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);
    };