Skip to main content

How to attach events

There are two options to attach events from the editor.

Option 1. Using the attachEditorEvent method

Starting from version 8.2, in the plugin code, define the attachEditorEvent method to add an event listener, a function that will be called whenever the specified event is delivered to the target.

Parameters

NameTypeDescription
idstringThe event name.
actionfunctionThe event listener.

Returns

This method doesn't return any data.

Example

Asc.plugin.attachEditorEvent("onAddComment", (data) => {
console.log(data);
});

Debouncing frequent events

Some events (like selection change) fire rapidly. Debounce to avoid excessive processing:

let debounceTimer;

Asc.plugin.attachEditorEvent("onTargetPositionChanged", () => {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
updatePluginUI();
}, 150);
});

Cleaning up on destroy

Always detach event listeners when the plugin is closed to avoid memory leaks:

Asc.plugin.onDestroy = () => {
Asc.plugin.detachEditorEvent("onTargetPositionChanged");
clearTimeout(debounceTimer);
};

Detaching events

To remove a previously attached event listener, use the detachEditorEvent method.

Parameters

NameTypeDescription
idstringThe event name.

Returns

This method doesn't return any data.

Example

Asc.plugin.detachEditorEvent("onAddComment");

Option 2. Using the attachEvent method

Deprecated

Starting from version 8.2, please use the attachEditorEvent method instead.

  1. In the config.json file, add the events parameter with the array of all the available events:

    {
    "events": ["onAddComment"]
    }
  2. In the plugin code, define the attachEvent method to add an event listener, a function that will be called whenever the specified event is delivered to the target:

    Asc.plugin.attachEvent(id, action);

    Parameters

    NameTypeDescription
    idstringThe event name.
    actionfunctionThe event listener.

    Returns

    This method doesn't return any data.

    Example

    Asc.plugin.attachEvent("onAddComment", (data) => {
    console.log(data);
    });

    You can also use the event_{event-name} method, where event_ is a prefix used for each event method, and {event-name} is a name of any event. For example:

    Asc.plugin.event_onAddComment = (data) => {
    console.log(data);
    };

    Such methods work the same way as the attachEvent method.