Martin Schulze Martin Schulze - 1 month ago 16
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 {
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);
}


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

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)
Comments