Skip to content

Instantly share code, notes, and snippets.

@cvan
Created December 5, 2013 23:24
Show Gist options
  • Save cvan/7815966 to your computer and use it in GitHub Desktop.
Save cvan/7815966 to your computer and use it in GitHub Desktop.
getters and setters
function makeSmart(obj) {
obj.__bound__ = {};
}
function isSmart(obj) {
return '__bound__' in obj;
}
function makeSmartProperty(obj, property) {
var oldVal = obj[property];
obj.__bound__[property] = [];
var bound = obj.__bound__;
// Apply magic
Object.defineProperty(obj, property, {
set: function(v) {
// set the stored value
bound[property].__value__ = v;
var fns = bound[property];
// fire our handlers
for (var i = 0; i < fns.length; i++) {
// for each fn, call fn(v)
fns[i](v);
}
},
get: function() {
return bound[property].__value__;
}
});
// apply an old value if it existed
if (typeof oldVal !== 'undefined') {
obj[property] = oldVal;
}
}
function isSmartProperty(obj, property) {
return obj.__bound__ && (property in obj.__bound__);
}
// wire data to DOM.
function link(obj, property, fn) {
// set up smartness
if (!isSmart(obj)) {
makeSmart(obj);
}
if (!isSmartProperty(obj, property)) {
makeSmartProperty(obj, property);
}
// call our handler once to initialize things
fn(obj[property]);
obj.__bound__[property].push(fn);
}
var manifest = {};
function renderJSON() {
// var prettyManifest = _.omit(manifest, '__bound__');
var prettyManifest = manifest;
console.log(JSON.stringify(prettyManifest));
}
link(manifest, 'name', renderJSON);
manifest.name = 'My Name';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment