丢失了"this"在tinymce的回调中 [英] lost "this" in callback from tinymce

查看:99
本文介绍了丢失了"this"在tinymce的回调中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an angular2 app with tinyMce as a HTML editor. The only problem is, I need to convert the URLs in the html through my REST API. To do that I attempted to use "urlconverter_callback" from tinyMce, but I loose the reference to this and get stuck:

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属性.

From the console I can see, that this is no longer pointing to my directive. As a result I can't access the innerValue property.

如何创建对指令有正确引用的回调?

How can I create a callback that will have a correct reference of my directive?

推荐答案

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

You can try one of these options:

1)在 tinymce.init

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)

这篇关于丢失了"this"在tinymce的回调中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆