Skip to content

Instantly share code, notes, and snippets.

@jonathanconway
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathanconway/501d1dee86c0c4342dc6 to your computer and use it in GitHub Desktop.
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. πŸ˜‹
/**
* @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