Skip to content

Instantly share code, notes, and snippets.

@bemson
Created September 12, 2010 23:45
Show Gist options
  • Save bemson/576620 to your computer and use it in GitHub Desktop.
Save bemson/576620 to your computer and use it in GitHub Desktop.
// the object to proxy
var obj = new SomeObject();
// standard proxy with same-name getter/setter
var stdProxy = {
getXsetY: function (value) {
if (arguments.length) {
if (typeof value === 'number') {
obj.y = value;
return true;
} else {
return false;
}
} else {
return obj.x;
}
}
}
// the same proxy using a GVS array in a Proxy constructor
var myPxy = new Proxy(obj, {
getXsetY: ['x', 'number', 'y']
});
function createProxyForAny(obj,cfg) {
var pxy = {},
i,
getterFnc = function (prop) {
return function () {
return obj[prop];
}
},
setterFnc = function (prop) {
return function (value) {
if (value) {
obj[prop] = value;
return true;
} else {
return false;
}
}
};
for (i in cfg) {
if (cfg.hasOwnProperty(i)) {
pxy['get' + i] = getterFnc(i);
pxy['set' + i] = setterFnc(i);
}
}
return pxy;
}
function createProxy(obj) {
return {
getProp: function () {
return obj.prop;
},
setProp: function (value) {
if (value) {
obj.prop = value;
return true;
} else {
return false;
}
}
};
}
@bemson
Copy link
Author

bemson commented Sep 13, 2010

These gists are embedded in http://learnings-bemson.blogspot.com/2010/09/learning-to-open-source-via-proxy.html to demonstrate the GVS pattern used by the Proxy constructor.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment