从 Decorator 中获取 Class 个实例

Get Class Instance from Within Decorator

我试图让我的思绪完全围绕装饰器,我有几个巧妙的想法,我可以在我正在处理的回流实现中使用它们。我想用一个动作标记商店的 class 方法,并且每次生成该动作时,它都知道调用任何用它标记的方法。

首先,我要标记 Store 方法:

@Action
public setData(data: FakeData) {
    console.log(this);
    this.state.data = data;
}

然后,在操作 class 中,我想在数组中注册该方法:

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));
    }
}

但是,在构造函数中我无权访问商店的实际实例。我能够获得构造函数,但我不确定我是否能够使用它来实现我的目标。也许我应该使所有存储严格静态而不是构造函数?

我确定我没有以正确的方式考虑这些装饰器,因此不胜感激!

Link to full code on Typescript Playground

看起来装饰器是在定义 class 时调用的,而不是实例化的。这意味着为了让它工作,我必须将所有存储方法设置为静态,并且实例不可访问:

@Action
public static setData(data: FakeData) {
    console.log(this);
    this.state.data = data;
}

完整的工作代码在这里:

Typescript Playground