Skip to content

Instantly share code, notes, and snippets.

@bttmly
Forked from olslash/gist:dd52c242a74f0daaa108
Created August 1, 2014 07:16
Show Gist options
  • Save bttmly/27ca93bdd16453f5874d to your computer and use it in GitHub Desktop.
Save bttmly/27ca93bdd16453f5874d to your computer and use it in GitHub Desktop.
var createObservedObject = function(callback) {
var obj = {};
var args = [].slice.call(arguments, 1);
for(var i in args) {
var thisPropertyName = args[i];
(function(thisPropertyName) {
obj['_' + thisPropertyName] = undefined;
Object.defineProperty(obj, thisPropertyName, {
get: function() {
return obj['_' + thisPropertyName];
},
set: function(val) {
callback('update', thisPropertyName, val);
obj['_' + thisPropertyName] = val;
}
});
})(thisPropertyName);
}
obj.addObservedProperty = function(propertyName) {
obj['_' + propertyName] = undefined;
Object.defineProperty(obj, propertyName, {
get: function() {
return obj['_' + propertyName];
},
set: function(val) {
callback('add', propertyName, val);
obj['_' + propertyName] = val;
}
});
};
return obj;
};
a = createObservedObject(console.log, 'arg1', 'arg2', 'arg3');
a.arg1 = 12;
console.log(a.arg1);
a.arg2 = 14;
console.log(a.arg2);
a.addObservedProperty('arg4');
a.arg4 = 16;
console.log(a.arg4);
a.unObserved = 'hi mom';
console.log(a.unObserved);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment