项目

事件

引言

编辑器会触发一些事件,你可以通过这些事件来定制其行为。让我们先来看看可用的所有事件。

可用事件列表

beforeCreate

在视图创建之前。

create

编辑器已准备好。

update

内容已更改。

selectionUpdate

选择范围已更改。

transaction

编辑器状态已改变。

focus

编辑器获得焦点。

blur

编辑器失去焦点。

destroy

编辑器正在销毁。

contentError

内容不符合模式。

注册事件监听器

方法 1:配置

可以直接在新的编辑器实例上定义事件监听器:

const editor = new Editor({
  onBeforeCreate({ editor }) {
    // 在视图创建之前。
  },
  onCreate({ editor }) {
    // 编辑器已准备好。
  },
  onUpdate({ editor }) {
    // 内容已更改。
  },
  onSelectionUpdate({ editor }) {
    // 选择范围已更改。
  },
  onTransaction({ editor, transaction }) {
    // 编辑器状态已改变。
  },
  onFocus({ editor, event }) {
    // 编辑器获得焦点。
  },
  onBlur({ editor, event }) {
    // 编辑器失去焦点。
  },
  onDestroy() {
    // 编辑器正在销毁。
  },
  onContentError({ editor, error, disableCollaboration }) {
    // 内容不符合模式。
  },
});

方法 2:绑定

或者你可以在运行中的编辑器实例上注册事件监听器:

绑定事件监听器

editor.on("beforeCreate", ({ editor }) => {
  // 在视图创建之前。
});

editor.on("create", ({ editor }) => {
  // 编辑器已准备好。
});

editor.on("update", ({ editor }) => {
  // 内容已更改。
});

editor.on("selectionUpdate", ({ editor }) => {
  // 选择范围已更改。
});

editor.on("transaction", ({ editor, transaction }) => {
  // 编辑器状态已改变。
});

editor.on("focus", ({ editor, event }) => {
  // 编辑器获得焦点。
});

editor.on("blur", ({ editor, event }) => {
  // 编辑器失去焦点。
});

editor.on("destroy", () => {
  // 编辑器正在销毁。
});

editor.on("contentError", ({ editor, error, disableCollaboration }) => {
  // 内容不符合模式。
});

解绑事件监听器

如果需要在某个时刻移除这些事件监听器,你应该使用 .on() 注册,然后用 .off() 来解绑。

const onUpdate = () => {
  // 内容已更改。
};

// 绑定 ...
editor.on("update", onUpdate);

// ... 并解绑。
editor.off("update", onUpdate);

方法 3:扩展

你也可以将事件监听器移动到自定义扩展(或节点、标记)中。这看起来像这样:

import { Extension } from "@tiptap/core";

const CustomExtension = Extension.create({
  onBeforeCreate({ editor }) {
    // 在视图创建之前。
  },
  onCreate({ editor }) {
    // 编辑器已准备好。
  },
  onUpdate({ editor }) {
    // 内容已更改。
  },
  onSelectionUpdate({ editor }) {
    // 选择范围已更改。
  },
  onTransaction({ editor, transaction }) {
    // 编辑器状态已改变。
  },
  onFocus({ editor, event }) {
    // 编辑器获得焦点。
  },
  onBlur({ editor, event }) {
    // 编辑器失去焦点。
  },
  onDestroy() {
    // 编辑器正在销毁。
  },
  onContentError({ editor, error, disableCollaboration }) {
    // 内容不符合模式。
  },
});
在本文档中