Last active
August 29, 2015 14:22
-
-
Save jonathanconway/501d1dee86c0c4342dc6 to your computer and use it in GitHub Desktop.
Returns an object with the same hierarchy of properties as the source object, but on invoking any of its properties, a getter is called instead. Might be useful to someone, somewhere, somehow. π
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
/** | |
* @name constructProxy | |
* | |
* @description | |
* From a source object, generates and returns a proxy object. When a property | |
* in the source object is invoked, it runs the function provided as the getter, | |
* passing it the name of the property invoked as well as the full expression | |
* that was invoked. Properties that are of type 'object' are simply copied over. | |
* | |
*/ | |
function constructProxy (source, proxy, getter, expressionPrefix) { | |
var prop, | |
props = []; | |
for (prop in source) { | |
props.push(prop); | |
} | |
props.forEach(function (prop) { | |
var sourceValue = source[prop]; | |
if (typeof sourceValue === 'object') { | |
proxy[prop] = {}; | |
constructProxy(sourceValue, proxy[prop], getter, /* expressionPrefix: */ ((expressionPrefix || '') + prop + '.')); | |
} | |
else { | |
Object.defineProperty(proxy, prop, { | |
get: function () { | |
return getter(prop, /* path: */ ((expressionPrefix || '') + prop)); | |
} | |
}); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment