Created
October 2, 2014 13:10
-
-
Save notcome/dcd17cab7e3099675794 to your computer and use it in GitHub Desktop.
KVO and Binding for JavaScript
This file contains hidden or 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 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