I'm attempting to get my mind completely wrapped around decorators, and I had a couple neat ideas where I could use them in a reflux implementation I'm working on. I want to tag a store's class method with an action, and any time that action is generated, it knows to call any methods tagged with it.
First, I want to tag the Store method:
@Action
public setData(data: FakeData) {
console.log(this);
this.state.data = data;
}
then, in the action class, I want to register that method in an array:
class Action {
private static methods: Method<FakeData>[] = [];
public static register(method: Method<FakeData>) {
this.methods.push(method);
}
constructor(payload: FakeData);
constructor(store: Store, method: string);
constructor(payload: any, method?: string, descriptor?: PropertyDescriptor) {
if (method) {
//TODO need actual instance of class here....
Action.register(payload[method].bind(payload));
return;
}
this.trigger(payload);
}
public get payload() {
return Math.random();
}
private trigger(payload: FakeData) {
Action.methods.forEach(m => m(payload));
}
}
However, inside the constructor I do not have access to the actual instance of the store. I am able to get the constructor, but I'm not sure I am able to use that to achieve my goal. Perhaps instead of a constructor, I should make all stores strictly static?
I'm sure I'm not thinking about these decorators the right way, so any insight is appreciated!
It looks like decorators are called when the class is defined, not instantiated. This means that in order for this to work, I had to set all store methods to static, and that instances are not accessible:
@Action
public static setData(data: FakeData) {
console.log(this);
this.state.data = data;
}
Full working code here:
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments