Skip to content

Instantly share code, notes, and snippets.

@notcome
Created October 2, 2014 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save notcome/dcd17cab7e3099675794 to your computer and use it in GitHub Desktop.
Save notcome/dcd17cab7e3099675794 to your computer and use it in GitHub Desktop.
KVO and Binding for JavaScript
function initWatchProperty (obj, key) {
if (obj['$$watchers$$' + key])
return;
Object.defineProperty(obj, key, {
get: function () {
return this['$$' + key];
},
set: function (val) {
var old = this['$$' + key];
this['$$' + key] = val;
this['$$watchers$$' + key].forEach(function (f) {
f(val, old);
});
}
});
obj['$$watchers$$' + key] = [];
}
function addListener (obj, key, cb) {
obj['$$watchers$$' + key].push(cb);
}
function bind (from, fromKey, to, toKey) {
initWatchProperty(from, fromKey);
addListener(from, fromKey, function (val) {
to[toKey] = val;
});
}
var a = {};
a.abc = 30;
bind(a, 'abc', a, 'bcd');
bind(a, 'abc', a, 'cde');
a.abc = 40;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment