Martin Schulze Martin Schulze - 1 year ago 124
Javascript Question

lost "this" in callback from tinymce

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 {
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);
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);

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?

Answer Source

You can try one of these options:

1) use bind within tinymce.init

urlconverter_callback: this.urlConverter.bind(this)

or within constructor:

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

2) use arrow function on the urlConverter method

urlConverter = (url, node, on_save): string => {

or within tinymce.init

urlconverter_callback: (url, node, on_save) => this.urlConverter(url, node, on_save)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download