Last active
August 29, 2015 13:56
-
-
Save gre/8964203 to your computer and use it in GitHub Desktop.
simple object model binding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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