ACE 编辑器 "Cannot read property 'getValue' of undefined"

ACE editor "Cannot read property 'getValue' of undefined"

我目前正在 Angular 中构建一个降价编辑器。

可以在此处找到一个 codesandbox:https://codesandbox.io/embed/angular-91d27


问题是我正在尝试获取当前值以便进一步使用它。 这个概念是,只要代码发生变化(onChange()),内容就会被放入 Angular 服务中。

出于测试目的,我想在更改时打印当前内容。

this.codeEditor.on("change", function(e) {
    const code = this.codeEditor.getValue();
    console.log(code);
});

现在,每当我输入内容时,都会出现以下错误:

ERROR TypeError: Cannot read property 'getValue' of undefined

如果之前有人遇到过这个问题,我很乐意提供帮助。
另外我想知道这是否是 "the right way" 来处理这个问题,或者是否有更好的选择。

每个新函数都定义了自己的 this 作用域。尝试改用 arrow functions。箭头函数在词法上绑定它们的上下文,因此 this 实际上指的是原始上下文。

this.codeEditor.on("change", (e) => {
    const code = this.codeEditor.getValue();
    console.log(code);
});