我试图在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行为?
到目前为止,我找到的有关该主题的唯一信息是这篇文章。
我正在尝试用 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)