Our simplified @bind decorator didn't work :( The getter is needed in order to defer binding until there is an instance to bind to, the simpler implementation actually bound methods to the prototype itself.

This commit is contained in:
Jason Miller
2018-03-29 23:13:03 -04:00
parent 5cfeefa86c
commit 8f452ddf6d

View File

@@ -34,6 +34,16 @@ export class When extends Component<WhenProps, WhenState> {
* f() instanceof C; // true
*/
export function bind(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
descriptor.value = descriptor.value.bind(target);
return descriptor;
return {
// the first time the prototype property is accessed for an instance,
// define an instance property pointing to the bound function.
// This effectively "caches" the bound prototype method as an instance property.
get() {
let boundFunction = descriptor.value.bind(this);
Object.defineProperty(this, propertyKey, {
value: boundFunction
});
return boundFunction;
}
};
}