Skip to content

Instantly share code, notes, and snippets.

@mjstahl
Created June 12, 2019 19:33
Show Gist options
  • Save mjstahl/5841e8e82e66449c74d1599b97996de0 to your computer and use it in GitHub Desktop.
Save mjstahl/5841e8e82e66449c74d1599b97996de0 to your computer and use it in GitHub Desktop.
Proxy the context of a class expression
// Thanks @BigAB
class Counter {
constructor() {
setTimeout(this.onTick.bind(this), 1000);
}
onTick() {
const now = new Date();
// want to call the set trap
this.hours = now.getHours();
// want to call the set trap
this.minutes = now.getMinutes();
// want to call the set trap
this.seconds = now.getSeconds();
}
}
function observeSets(instance) {
const p = new Proxy(instance, {
set(target, property, value, receiver) {
console.log('SETTING', property, value);
return Reflect.set(target, property, value, receiver);
},
});
return p;
}
function proxyClass(ClassOrConstructor) {
return new Proxy(ClassOrConstructor, {
construct(target, argumentsList, newTarget) {
return Reflect.construct(
function() {
const p = Object.create(target.prototype);
const pp = observeSets(p);
let instance = pp;
instance = target.prototype.constructor.call(pp);
return instance;
},
argumentsList,
newTarget
);
},
});
}
const ProxiedCounter = proxyClass(Counter);
const counter = new ProxiedCounter();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment