-
-
Save bttmly/27ca93bdd16453f5874d to your computer and use it in GitHub Desktop.
This file contains 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
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