Skip to content

Instantly share code, notes, and snippets.

@alexanderson1993
Created August 17, 2020 14:40
Show Gist options
  • Save alexanderson1993/14602f908937536b93ddb492a3b41233 to your computer and use it in GitHub Desktop.
Save alexanderson1993/14602f908937536b93ddb492a3b41233 to your computer and use it in GitHub Desktop.
What not to do with proxies.
// Create a symbol for our proxy
let isProxy = Symbol("isProxy");
const handler = {
get(target, key) {
// Override access if we are checking if the object is already a proxy
if (key === isProxy) return true;
if (
// Don't wrap it again if the object is already a proxy
!target[isProxy] &&
// Make sure it's an actual property, not one from the prototype chain
Object.getOwnPropertyDescriptor(target, key) &&
typeof target[key] === "object" &&
target[key] !== null &&
// Dates are an explicit exception, and shouldn't have proxies applied
!(target[key] instanceof Date)
) {
return new Proxy(target[key], handler);
} else {
return target[key];
}
},
set(target, name, value) {
// Do stuff here
return true;
},
deleteProperty(target, prop) {
// Do stuff here
return true;
},
};
const myProxy = new Proxy(dataObject, handler)
// DON'T USE THIS. It might perform or behave poorly in certain circumstances.
const handler = {
get(target, key) {
if (key === isProxy) return true;
if (
typeof target[key] === "object" &&
target[key] !== null
) {
return new Proxy(target[key], handler);
} else {
return target[key];
}
},
set(target, name, value) {
// Do stuff here
return true;
},
deleteProperty(target, prop) {
// Do stuff here
return true;
},
};
const myProxy = new Proxy(dataObject, handler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment