Tiptap 中的事件
编辑器会触发一些不同的事件供你挂载。让我们先看看所有可用的事件。
可用事件列表
| 事件名称 | 描述 |
|---|---|
beforeCreate | 在编辑器视图创建之前。 |
create | 当编辑器完全初始化并准备就绪时。 |
update | 当内容发生变化时。 |
selectionUpdate | 当选择在编辑器中更改时。 |
transaction | 当编辑器状态因任何操作而变化时。 |
focus | 当编辑器获得焦点时。 |
blur | 当编辑器失去焦点时。 |
destroy | 当编辑器实例正在被销毁时。 |
paste | 当内容被粘贴到编辑器中时。 |
drop | 当内容被拖放到编辑器中时。 |
delete | 当内容从编辑器中删除时。 |
contentError | 内容与模式不匹配。 在这里阅读更多 |
注册事件监听器
有三种方法可以注册事件监听器。
选项 1:配置
你可以在新的编辑器实例上立即定义事件监听器:
const editor = new Editor({
onBeforeCreate({ editor }) {
// 在视图创建之前。
},
onCreate({ editor }) {
// 编辑器已准备好。
},
onUpdate({ editor }) {
// 内容已改变。
},
onSelectionUpdate({ editor }) {
// 选择已改变。
},
onTransaction({ editor, transaction }) {
// 编辑器状态已改变。
},
onFocus({ editor, event }) {
// 编辑器获得了焦点。
},
onBlur({ editor, event }) {
// 编辑器不再获得焦点。
},
onDestroy() {
// 编辑器正在被销毁。
},
onPaste(event: ClipboardEvent, slice: Slice) {
// 内容正在被粘贴到编辑器中。
},
onDrop(event: DragEvent, slice: Slice, moved: boolean) {
// 内容正在被拖放到编辑器中。
},
onDelete({ type, deletedRange, newRange, partial, node, mark, from, to, newFrom, newTo }) {
// 内容已从编辑器中删除(节点或标记)。
},
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('paste', ({ event, slice, editor }) => {
// 内容正在被粘贴到编辑器中。
})
editor.on('drop', ({ editor, event, slice, moved }) => {
// 内容正在被拖放到编辑器中。
})
editor.on('delete', ({ type, deletedRange, newRange, partial, node, mark }) => {
// 内容已从编辑器中删除(节点或标记)。
})
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() {
// 编辑器正在被销毁。
},
onPaste(event: ClipboardEvent, slice: Slice) {
// 内容正在被粘贴到编辑器中。
},
onDrop(event: DragEvent, slice: Slice, moved: boolean) {
// 内容正在被拖放到编辑器中。
},
onDelete({ type, deletedRange, newRange, partial, node, mark }) {
// 内容已从编辑器中删除(节点或标记)。
},
onContentError({ editor, error, disableCollaboration }) {
// 编辑器内容与模式不匹配。
},
})