相关疑难解决方法(0)

TypeScript中是否存在"this"的别名?

我试图在TypeScript中编写一个类,该类具有一个定义的方法,该方法充当jQuery事件的事件处理程序回调.

class Editor {
    textarea: JQuery;

    constructor(public id: string) {
        this.textarea = $(id);
        this.textarea.focusin(onFocusIn);
    }

    onFocusIn(e: JQueryEventObject) {
        var height = this.textarea.css('height'); // <-- This is not good.
    }
}
Run Code Online (Sandbox Code Playgroud)

在onFocusIn事件处理程序中,TypeScript将"this"视为该类的"this".但是,jQuery会覆盖此引用并将其设置为与事件关联的DOM对象.

另一种方法是在构造函数中将lambda定义为事件处理程序,在这种情况下,TypeScript会创建一种带有隐藏_this别名的闭包.

class Editor {
    textarea: JQuery;

    constructor(public id: string) {
        this.textarea = $(id);
        this.textarea.focusin((e) => {
            var height = this.textarea.css('height'); // <-- This is good.
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,是否有另一种方法来使用TypeScript在基于方法的事件处理程序中访问此引用,以克服此jQuery行为?

jquery typescript

73
推荐指数
4
解决办法
3万
查看次数

使用 Vuex 和打字稿的正确方法是什么?

到目前为止,我找到的有关该主题的唯一信息是这篇文章

我正在尝试用 2 个模块实现商店。

export interface RootState {
    /** root state props **/
}

const store: StoreOptions<RootState> = {
    modules: {
        foo,
        bar,
    },
};

export default new Vuex.Store<RootState>(store);
Run Code Online (Sandbox Code Playgroud)

然后我有两个模块:

export interface FooState {
    //(...)    
}

export const foo: Module<FooState, RootState> = {
    //(...)
};

export interface BarState {
    //(...)    
}

export const bar: Module<BarState, RootState> = {
    //(...)
};
Run Code Online (Sandbox Code Playgroud)

一切正常,直到我遇到一种情况,我需要一个来自 foo 模块的 getter 来访问 bar 状态:

export const getters: GetterTree<FooState, RootState> = {
    getInfo: (state, {}, rootState) …
Run Code Online (Sandbox Code Playgroud)

typescript vue.js vuex

22
推荐指数
1
解决办法
2万
查看次数

标签 统计

typescript ×2

jquery ×1

vue.js ×1

vuex ×1