Skip to content

Instantly share code, notes, and snippets.

@gre gre/dog.js
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.