Created
October 6, 2019 16:52
-
-
Save pfeilbr/f33a5228d570a45d627894a6374030f2 to your computer and use it in GitHub Desktop.
example of extendable 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
(() => { | |
class RectProxy { | |
props = { | |
position: (newPos, twojs) => { | |
twojs.doWork(); | |
}, | |
innerColor: (newColor, twojs) => { | |
twojs.doWork(); | |
} | |
} | |
constructor(width, height) { | |
this.twojs = { | |
doWork: () => console.log("twojs.doWork() called"), | |
updateUI: () => console.log("twojs.updateUI() called") | |
} | |
return new Proxy(this, { | |
set: (target, key, value, proxy) => { | |
if (Reflect.has(this.props, key)) { | |
this.props[key](value, this.twojs) | |
target[`_${key}`] = value; | |
target.updateUI(); | |
} else if (Reflect.has(target, key)) { | |
Reflect.set(target, key, value); | |
} | |
return true; | |
}, | |
get: function(target, prop, receiver) { | |
if (Reflect.has(target, `_${prop}`)) { | |
return target[`_${prop}`] | |
} else { | |
return Reflect.get(...arguments); | |
} | |
} | |
}); | |
} | |
updateUI = () => { | |
this.twojs.updateUI() | |
} | |
} | |
class Rect extends RectProxy {} | |
let rect1 = new Rect(); | |
rect1.position = {x: 15, y:15}; | |
console.log(`rect1.position = ${JSON.stringify(rect1.position)}`) | |
rect1.innerColor = {red: 255, green: 0, blue: 0}; | |
console.log(`rect1.innerColor = ${JSON.stringify(rect1.innerColor)}`) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment