如何从 CKEditor 5 捕获外部事件?

问题描述

我正在关注 this guideCKEditor 5 编写自定义插件。我实际上创建了一个名为 Insertimage 的类,它扩展了 Plugin 类。然后,我将 Insertimage 与编辑器工具栏和支持插件相关联,并且运行良好。

问题是我必须打开一个包含列表中图像列表的模式,到目前为止我是这样做的:

import Plugin from '@ckeditor/ckeditor5-core/src/plugin'
import Image from '@ckeditor/ckeditor5-image/src/image';
import imageIcon from '@ckeditor/ckeditor5-core/theme/icons/image.svg';
import ButtonView from '@ckeditor/ckeditor5-ui/src/button/buttonview';

class Insertimage extends Plugin {
    init() {
        const editor = this.editor;

        editor.ui.componentFactory.add( 'insertimage',locale => {
            const view = new ButtonView( locale );

            view.set( {
                label: 'Insert image',icon: imageIcon,tooltip: true
            } );

            // Callback executed once the image is clicked.
            view.on( 'execute',() => {
                
                // open the modal which contains a list of image
                $('#modal-media-browse').modal('show');
                
            } );

            return view;
        } );
    }
}

当我单击编辑器的图像按钮时,模态正确打开,但我不明白如何从自定义模态传递图像 url。本质上,在我从模式中选择了图像(这是一个简单的列表)之后,我有一个按钮可以让我获取图像的属性,如 srcid 等......

如何将此自定义属性传递给编辑器?

CKEditor 教程中显示的示例描述了如何将内容插入:

const imageUrl = prompt( 'Image URL' );

然后我们有:

editor.model.change( writer => {
    const imageElement = writer.createElement( 'image',{
        src: imageUrl
    } );


    // Insert the image in the current selection location.
    editor.model.insertContent( imageElement,editor.model.document.selection );
} );

但是如何在外部脚本中应用相同的逻辑?我想我应该触发一个事件,编辑器必须捕获该事件并获取该事件调度的图像的 src。

有人能告诉我如何将图像 url 从外部脚本传递给编辑器吗?

解决方法

我的解决方法:

class InsertImage extends Plugin {
    init() {
        const editor = this.editor;

        editor.ui.componentFactory.add( 'insertImage',locale => {
            const view = new ButtonView( locale );

            view.set( {
                label: 'Insert image',icon: imageIcon,tooltip: true
            } );

            // Callback executed once the image is clicked.
            view.on( 'execute',() => {
                
                // apre la modal per la selezione del media
                $('#modal-media-browse').modal('show');

                $('#modal-media-browse').on('hidden.bs.modal',function() {
                    
                    editor.model.change(writer => {
                        const imageElement = writer.createElement('image',{
                            src: $(this).attr('data-src')
                        });
                        editor.model.insertContent(imageElement,editor.model.document.selection);
                    })
                });
            } );

            return view;
        } );
    }
}

我将图像 src 属性存储在模态上,因此当模态关闭时,会在插件内部触发事件并将图像添加到编辑器中。