Skip to content

Handle more DOM events

Jiuqing Song edited this page Mar 8, 2018 · 1 revision

Go back to Create your own plugin

Editor class already added event handler for most common DOM events and dispatch them to plugin, and plugins can handle them in EditorPlugin.onPluginEvent() method. However, if you want to handle more DOM events which are not already handled by editor, you can use Editor.addDomEventHandler() method.

public addDomEventHandler(eventName: string, handler: (event: UIEvent) => void): () => void;

eventName parameter is the name of the event you'd like to handle.

handler parameter is a callback function which will be called when the event is fired.

Return value of this method is a dispose function. You need to call this function when you want to remove the event listener, in most case, this happens in dispose() method of a plugin.

For example, Paste plugin is using this method to handle HTML paste event:

class Paste implements EditorPlugin {
    private pasteDisposer: () => void;

    public initialize(editor: Editor) {
        this.editor = editor;
        this.pasteDisposer = editor.addDomEventHandler('paste', this.onPaste);
    }

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

    private onPaste = (event: Event) => {
        // Handle the event
    };
}

Here is a list of the difference between EditorPlugin.onPluginEvent() method and Editor.addDomEventHandler() method:

onPluginEvent addDomEventHandler
Event type Predefined events only Any DOM events
How to add Automatically Need to call method explicitly
How to remove Automatically Need to call disposer function explicitly
Exclusiveness Supported Not supported
Dispatch order Same with the order of plugins Unpredictable
When add Editor initialization When the method is called
When remove Editor disposing When the disposer is called

EditorPlugin.onPluginEvent() already handled most of the initializing/disposing work for you, so if the plugin you want to handle is already supported by EditorPlugin.onPluginEvent(), you should use it. Editor.addDomEventHandler() provides the most flexibility, so if the event you'd like to handle is not supported by EditorPlugin.onPluginEvent(), or you need your customized behavior, you can use Editor.addDomEventHandler().

More info

Package: roosterjs-editor-core

Support from: 6.5.0

Source code: Editor.ts