Skip to content

Instantly share code, notes, and snippets.

@olslash
Last active August 29, 2015 14:04
Show Gist options
  • Save olslash/dd52c242a74f0daaa108 to your computer and use it in GitHub Desktop.
Save olslash/dd52c242a74f0daaa108 to your computer and use it in GitHub Desktop.
budget observable
var createObservedObject = function(callback) {
var obj = {};
var args = [].slice.call(arguments, 1);
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;
}
});
};
for (var i in args) {
var thisPropertyName = args[i];
obj.addObservedProperty(thisPropertyName)
}
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