Created
August 17, 2020 14:40
-
-
Save alexanderson1993/14602f908937536b93ddb492a3b41233 to your computer and use it in GitHub Desktop.
What not to do with proxies.
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
// 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) |
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
// 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