Created
November 14, 2021 19:54
-
-
Save francoisgeorgy/19b3db6037f6ccf95208db83ae8e6435 to your computer and use it in GitHub Desktop.
#javascript #proxy
This file contains hidden or 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
| // https://reflect.run/articles/reflection-at-reflect/ | |
| // PROXY example 1 : | |
| // makeStoreAccessProxy.ts | |
| const makeStoreAccessProxy = (obj: Object) => { | |
| return new Proxy(obj, { | |
| get(target, key, receiver) { | |
| console.log(`GOT FIELD ${key}`) | |
| return Reflect.get(target, key) | |
| }, | |
| }) | |
| } | |
| // usage: | |
| window.globalSession = makeStoreAccessProxy(fetchSession()) | |
| // PROXY example 2 : | |
| const someFramework = document.querySelector('#framework-root').framework | |
| someFramework.blockingUpdate = new Proxy(someFramework.blockingUpdate, { | |
| apply(target, thisArg, argArray) { | |
| // Here we'll take some action whenever a call to blockingUpdate() is made | |
| console.log('Intercepted a call to blockingUpdate()') | |
| Reflect.apply(target, thisArg, argArray) | |
| }, | |
| }) | |
| someFramework.asyncUpdate = new Proxy(someFramework.asyncUpdate, { | |
| apply(target, thisArg, argArray) { | |
| // Here we'll redefine calls to asyncUpdate() to instead invoke blockingUpdate() | |
| Reflect.apply(someFramework.blockingUpdate, thisArg, argArray) | |
| }, | |
| }) | |
| // REFLECT example : | |
| // First we'll store a reference to the original property descriptor for the | |
| // HTMLImageElement's src field | |
| const originalImgSrc = Reflect.getOwnPropertyDescriptor(HTMLImageElement.prototype, 'src') | |
| // Then we'll overwrite the HTMLImageElement prototype's "src" property and trap | |
| // calls to that field's get() and set() methods | |
| Reflect.defineProperty(HTMLImageElement.prototype, 'src', { | |
| get() { | |
| // When <someImg>.src is called anywhere, we'll log some information, then call the | |
| // target's get() method also using the Reflect API | |
| console.log('getting the src') | |
| return Reflect.apply(originalImgSrc.get, this, []) | |
| }, | |
| set(value) { | |
| // When <someImg>.src = 'something' is called anywhere, we'll log some information, then call the | |
| // target's set() method also using the Reflect API | |
| console.log(`setting src to ${value}`) | |
| return Reflect.apply(originalImgSrc.set, this, [value]) | |
| }, | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment