Skip to content

Instantly share code, notes, and snippets.

@gre
Last active August 29, 2015 13:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gre/8964203 to your computer and use it in GitHub Desktop.
Save gre/8964203 to your computer and use it in GitHub Desktop.
simple object model binding
function Dog (name, age) {
this._f = {};
this._prop("name", name);
this._prop("age", age);
}
Dog.prototype = {
_prop: function (prop, initialValue) {
var self = this;
Object.defineProperty(this, prop, {
get: function () {
return initialValue;
},
set: function (v) {
initialValue = v;
self._dispatchChange(prop, v);
}
});
},
_dispatchChange: function (prop, s) {
(this._f[prop]||[]).forEach(function (f) {
f(s);
});
},
onChange: function (prop, f) {
this._f[prop] = (this._f[prop]||[]).concat([ f ]);
},
syncChange: function (prop, f) { // bind on change and call once with the current value
this.onChange(prop, f);
f(this[prop]);
}
};
var dog = new Dog("max", 10);
dog.syncChange("age", function (age) {
document.body.textContent = age+" years old";
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment