Created
September 12, 2010 23:45
-
-
Save bemson/576620 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
// 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'] | |
}); |
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
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; | |
} |
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
function createProxy(obj) { | |
return { | |
getProp: function () { | |
return obj.prop; | |
}, | |
setProp: function (value) { | |
if (value) { | |
obj.prop = value; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.