CKEditor5监听变化事件更新模型

CKEditor5 Listening to Change Event and Updating Model

我正在尝试在 CkEditor5 中创建一个包含两部分的小部件:

1) 公式纯文本版本的输入(我想保存在模型和 getData 上的内容)

2) 使用 KaTeX 呈现的文本公式的实时预览(实际应该在编辑器中显示的内容)。

我运行变成了a bug with the WidgetToolbar,所以我现在的做法就是简单的插入两个自定义块元素,其中一个作为输入,另一个作为预览。当文档更改时,我试图检查输入的内容是否已更改,并将其插入到预览中(我还没有真正 t运行sforming 它)。

这是我用来插入元素的代码(连接到自定义按钮):

function createFormula( writer, editor ) {
    const formula = writer.createElement('formula');
    const formulaInput = writer.createElement('formulaInput');
    const formulaPreview = writer.createElement('formulaPreview');
    let formulaInputValue = null;

    editor.model.document.on('change:data', (eventInfo) => {

      if (formulaInput && formulaInput._children && formulaInput._children._nodes && formulaInput._children._nodes[0]) {
        let newValue = formulaInput._children._nodes[0]._data;

        if(formulaInputValue !== newValue) {
            formulaInputValue = newValue;
            writer.insertText(formulaInputValue, formulaPreview);
        }

      }


    });


    writer.append( formulaInput, formula );
    writer.append( formulaPreview, formula );

    return formula;
}

尽管 writer.insertText 出现在 editor.model.document.on('change:data') 中,但我收到一条错误消息:

Uncaught CKEditorError: writer-incorrect-use: Trying to use a writer outside the change() block

我对如何完成侦听一个元素的变化并将内容插入另一个元素的任务感到困惑。我注意到有一个 'change' event associated with elements,但这不是一种可以用来监听元素变化的实际方法。如果 document.on('change:data') 不算作更改块,那算什么呢?有没有更好的聆听方式?有这方面的例子吗?我一直在浏览 CkEditor5 文档和其他插件,但我还没有找到任何有用的示例。

要修改模型,请始终使用 model.change()。如果您传递 writer 以在此调用之外使用 - 即在某些异步任务中它将失败,因为模型更改是同步的。在这种情况下,我建议使用 editor.model.change( writer => writer.insertText() ) 并且根本不要传递 writer 实例。