在 tinymce 的回调中丢失 "this"

lost "this" in callback from tinymce

我有一个带有 tinyMce 作为 HTML 编辑器的 angular2 应用程序。唯一的问题是,我需要通过我的 REST API 转换 html 中的 URL。为此,我尝试使用 tinyMce 中的 "urlconverter_callback",但我丢失了对此的引用并卡住了:

ngAfterViewInit(): void {
    console.log('tinymce');
    tinymce.init({
        selector: `[data-tinymce-uniqueid=${this.uniqueId}]`,
    theme: "modern",
    skin: 'light',
    height: 768,
    toolbar: 'undo redo | styleselect | bold italic | link image | code',
    plugins: 'code',
        schema: 'html5',
    urlconverter_callback: this.urlConverter,
        setup: ed => {
            ed.on('init', ed2 => {
                if (this.innerValue) ed2.target.setContent(this.innerValue.text);
                this.init = true;
            });
        }
    });

    // I chose to send an update on blur, you may choose otherwise
    tinymce.activeEditor.on('blur', () => this.updateValue());
}

urlConverter(url, node, on_save): string {
    console.log("TinyDirective.urlConverter(%o, %o, %o)", url, node, on_save);
    console.log("TinyDirective.urlConverter: this = %o", this);
    console.log("TinyDirective.urlConverter: this.innerValue = %o", this.innerValue);
    return this.innerValue.url_converter(url);
}

从控制台我可以看到,这不再指向我的指令。结果我无法访问 innerValue 属性.

如何创建一个正确引用我的指令的回调?

您可以尝试以下选项之一:

1) 在 tinymce.init

内使用 bind
urlconverter_callback: this.urlConverter.bind(this)

或在构造函数中:

constuctor() {
  this.urlConverter = this.urlConverter.bind(this);
}

2) 在urlConverter方法

上使用箭头函数
urlConverter = (url, node, on_save): string => {
  ...
}

tinymce.init

urlconverter_callback: (url, node, on_save) => this.urlConverter(url, node, on_save)