Skip to content

Dispose an editor

Jiuqing Song edited this page Nov 13, 2020 · 3 revisions

Go back to How to use

Once we finished using an editor, we should call Editor.dispose() to dispose it.

Editor.dispose() method

Editor class provides dispose() method to dispose an editor.

public dispose();

This method will do:

  1. Call dispose() method of each plugin so that plugins know that editor is being disposed and they can dispose themselves first
  2. Remove DOM event listeners
  3. Dispose custom data attached to editor if any
  4. Remove the "contenteditable" attribute from the editor content DIV if EditorOptions.omitContentEditable is not set to true, so that the content DIV is reset to non-editable mode.

This method will NOT do:

  1. Remove the content DIV from DOM tree.
  2. clear content inside content DIV.

So, to release any allocated memory and let plugins have chance to get disposed, we should always call dispose() method to make sure editor is disposed before unload it.

Check disposed

Sometimes we need to know if an editor is already disposed, for example, from a timeout callback which may still have reference to editor. Editor class provides isDisposed() method:

public isDisposed(): boolean;

If an editor is already disposed, do not invoke any method from this editor, otherwise it will cause runtime exception. So it is a best practice to always check isDisposed() before using editor inside any async callback function.

Re-enable editor

Once editor is disposed, there is no way to re-enable the same editor object. But what you can do is to call createEditor() or new Editor() again with the same content DIV to make it editable. This allows us to switch a content DIV between editable mode and non-editable mode. For example:

class EditorWrapper {
    private editor: Editor;

    constructor(
        private contentDiv: HTMLDivElement,
        private plugins: EditorPlugin[]
    ) {
        this.enableEditing();
    }

    public enableEditing() {
        if (!this.editor) {
            this.editor = createEditor(this.contentDiv, this.plugins);
        }
    }

    public disableEditing() {
        if (this.editor) {
            this.editor.dispose();
            this.editor = null;
        }
    }
}