// library code --------------------------------------------------------------------------------
const options = {},
optionsRevocable = Proxy.revocable(options, {
set (obj, prop, value) {
if (prop === 'name') {
if (typeof value !== 'string' || value === '') {
throw new TypeError('"name" option should be a non-emtpy string');
}
} else if (prop === 'age') {
if (typeof value !== 'number' || value < 0 || value > 200) {
throw new TypeError('"age" option should be a number between 0 and 200');
}
} else {
throw new TypeError('The only valid options are "name" and "age"');
}
Reflect.set(obj, prop, value);
}
});
// sending the validated options proxy to the client
clientSetOptionsEventHandler(optionsRevocable.proxy);
// options arrived
console.log(options);
// revoking the client's access
optionsRevocable.revoke();
// simulating client actions afterwards
clientSometimeLater();
// client code --------------------------------------------------------------------------------
var globalOpts;
function clientSetOptionsEventHandler(opts) {
opts.name = 'Bob';
opts.age = 25;
//opts.age = 'old'; // TypeError: "age" option should be a number between 0 and 200
//opts.height = 182; // TypeError: The only valid options are "name" and "age"
// keeping the reference for stupid/harmful reasons
globalOpts = opts;
}
function clientSometimeLater() {
// trying to change it outside of the event handler
//globalOpts.name = 'Not Bob'; // TypeError: Cannot perform 'set' on a proxy that has been revoked
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.