7

我正在从 CKEditor 4.7 迁移到 5。

在 CKE4 中,我会做这样的事情: CKEDITOR.replace('text_area'); 然后在另一个 JS 函数中,我可以通过 CKEDITOR.instances.text_area.getData().

但CKE5似乎没有功能ClassicEditor.instances或类似的东西。

我知道我可以将编辑器实例存储为全局 JS 变量,但是我正在使用的代码在通用函数中创建编辑器,所以我不能只创建一个全局变量,因为我不知道编辑器的名称先验。屏幕上还可以同时有多个处于活动状态的编辑器。

CKE5 中是否没有类似于旧的可以让我从它替换的 textareainstances中获取编辑器实例的旧版本?id

我想我可以创建自己的全局数组来保存编辑器实例,但如果有内置的东西并得到更好的支持,我宁愿不这样做

4

3 回答 3

18

这个问题已经在How to get data from CKEDITOR5 instance 中得到解答,但是让我们在这里考虑一个有多个编辑器实例的情况。

我想我可以创建自己的全局数组来保存编辑器实例,但如果有内置的东西并得到更好的支持,我宁愿不这样做

没有编辑器实例的存储库。我们可以添加它,但我们认为这不是必不可少的功能。这实际上是人们在 CKEditor 4 中习惯的东西,所以他们从未想过并学会如何自己管理编辑器。

此外,没有单个实例存储库的原因是根本没有中央单例对象。您可以实现多个编辑器类,它们不必相互了解。要建立一个存储库,我们需要再次集中这些东西。

因此,正如您自己指出的那样,存储所有实例的一种简单方法是使用这些实例的全局(在您的应用程序或模块中,不一定是“全局 JS 变量”)映射。

这些实例的键可以是您初始化编辑器的元素的 id:

const editors = {}; // You can also use new Map() if you use ES6.

function createEditor( elementId ) {
    return ClassicEditor
        .create( document.getElementById( elementId ) )
        .then( editor => {
            editors[ elementId ] = editor;
        } )
        .catch( err => console.error( err.stack ) );
}

// In real life, you may also need to take care of the returned promises.
createEditor( 'editor1' );
createEditor( 'editor2' );

// Later on:
editors.editor1.getData();

如果您不为 DOM 中的元素分配 id 怎么办?如果你使用 ES6,那么这不是问题。元素和其他对象一样,可以是地图的键。

const editors = new Map();

function createEditor( elementToReplace ) {
    return ClassicEditor
        .create( elementToReplace )
        .then( editor => {
            editors.set( elementToReplace, editor );
        } )
        .catch( err => console.error( err.stack ) );
}

// In real life, you may also need to take care of the returned promises.
createEditor( textarea1 );
createEditor( textarea2 );

// Later on:
editors.get( textarea1 ).getData();

如果你不能使用 ES6,那么你需要做更多的事情——例如动态地data-editor-id为你创建编辑器的元素分配一些属性。

于 2018-02-08T09:56:36.580 回答
4

这不是我第一次尝试提醒自己如何在生产网站上访问 CKEditor 实例,只需通过开发人员控制台访问 DOM,所以提醒自己 ;)

https://ckeditor.com/docs/ckeditor5/latest/builds/guides/faq.html#how-to-get-the-editor-instance-object-from-the-dom-element

ckeditorInstance可以使用CKEditor 5 正在使用的 contenteditable 元素上可用的属性访问编辑器实例。您可以通过例如.ck-editor__editable类访问此 DOM 元素。

// A reference to the editor editable element in the DOM.
const domEditableElement = document.querySelector( '.ck-editor__editable' );

// Get the editor instance from the editable element.
const editorInstance = domEditableElement.ckeditorInstance;

// Now you can use the editor instance API.
editorInstance.setData( '<p>Hello world!<p>' );
于 2020-05-27T11:57:33.153 回答
0

使用 jQuery 和类选择器运行编辑器的多个副本:

$( '.editor' ).each( function() {
    InlineEditor
        .create( this )
        .catch( error => {
            console.error( error );
        } );
});
于 2021-09-25T16:47:13.077 回答