我将DOM事件绑定到事件处理函数(请参见下文)。这种绑定发生在需要通过this.parent
调用其父类的子组件中。
我的问题当然是在这样的函数中将this
重新绑定到触发了事件的对象(在这种情况下,就是#document
)。这使我无法在函数本身内部执行this.parent
,并且无法更改函数原型。 我该怎么做才能在this
函数中跟踪原始_keydownHandler(e)
?(是的,我听说过箭头函数,但是这里不是一个选择)
此处的代码:
"use strict";
export class EventHandler {
constructor(parent) {
this.parent = parent;
}
bindEvent() {
document.onkeydown = SomeOtherClass.keydownHandler;
}
printParentValue() {
console.log("Value from child:", this.parent.someValue);
}
callParentFn() {
this.parent.someFn();
}
}
class SomeOtherClass {
keydownHandler(e) {
console.log(this.parent.someValue); // I want to access the EventHandler's parent from there
}
}
父母的行为大致如下:
"use strict";
import { EventHandler } from "./events.js";
class Parent {
constructor() {
this.someValue = 3;
this.eH = new EventHandler(this);
this.eH.bindEvent();
}
someFn() {
console.log("Value from parent:", this.someValue);
}
test() {
this.eH.printParentValue();
this.eH.callParentFn();
}
}
const parent = new Parent();
parent.test();
如预期的那样,parent.test()
方法很好,但是我无法从Parent.someValue
访问_keydownHandler(e)
。