Contribute to this guide

guide(旧版) API 和事件

⚠️ 我们更改了安装方法,此旧版指南保留供用户参考。如果您想了解有关这些更改的更多信息,请参阅迁移到新的安装方法指南。

CKEditor 5 API 允许开发人员与编辑器及其插件进行交互以创建新的行为。通过事件系统,您可以调整对正在发生的特定操作的反应。

# 使用 API

API 允许您对编辑器及其内容执行多种操作

editor.model.change( writer => {
    // Move selection to the end of the document.
    writer.setSelection(
        writer.createPositionAt( editor.model.document.getRoot(), 'end' )
    );

    // Execute the enter command.
    editor.execute( 'enter' );

    // Insert text.
    editor.model.change( writer => {
        editor.model.insertContent( writer.createText( 'The End!' ) );
    } );
} );

在上面的示例中,您使用选择和命令,并使用编辑器的模型更改内容。所有这些都可以通过一个撤消步骤恢复。这是一个 API 功能的简单示例。

查看更多关于如何使用 API 的示例或深入了解我们的分步教程

# 使用事件

编辑器实例还可以用于为事件设置监听器。编辑器中的每个插件都会发布您可以订阅和交互的事件。例如,Document#change:data 事件会在文档以在编辑器数据中“可见”的方式更改时触发

editor.model.document.on( 'change:data', () => {
    console.log( 'The data has changed!' );
} );

事件可用于更改编辑器的行为。想象一下,用户想要将Enter键击与Shift + Enter组合互换,因此Shift + Enter 将插入一个新的块,而Enter 将插入一个 <br>

editor.editing.view.document.on( 'enter', ( evt, data ) => {
    data.preventDefault();
    evt.stop();

    if ( data.isSoft ) {
            editor.execute( 'enter' );
            editor.editing.view.scrollToTheSelection();

            return;
    }

    editor.execute( 'shiftEnter' );
    editor.editing.view.scrollToTheSelection();
}, { priority: 'high' } );

您可以在框架文档中找到有关事件的更多信息。