当 CKEditor 5 中的内容发生变化时监听事件

Listen to event fired when the content has changed in CKEditor 5

如何在 ckeditor5 中收听 "input" 事件?我希望能够像这样使用 Observables

Observable.fromEvent(this.editor, "input").debounceTime(250).subscribe(() => {});

到目前为止,我已经能够听到像这样的一些事件:

Observable.fromEvent(this.editor.editing.view, 'selectionChangeDone').subscribe(() => { });

但我找不到在编辑器中数据更改后立即触发的事件的名称。我试过 "change" 但它只在编辑器获得或失去焦点时触发。

自 CKEditor5 v11.0.0(自 2018 年 7 月 21 日起)

可能需要的是由编辑文档触发的Document#change:data事件。

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

当文档以编辑器数据中 "visible" 的方式更改时,将触发此事件。还有一组变化,比如选择位置的变化,不影响editor.getData()结果的标记变化。要收听所有这些变化,您可以使用更广泛的 Document#change 事件:

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

CKEditor5 v11.0.0 之前的版本

可能需要的是由编辑文档触发的change事件。

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

正如该事件的文档所述:

Fired after each enqueueChange() block or the outermost change() block was executed and the document was changed during that block's execution.

The changes which this event will cover include:

  • document structure changes,
  • selection changes,
  • marker changes.

If you want to be notified about all these changes, then simply listen to this event like this:

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

If, however, you only want to be notified about structure changes, then check whether the differ contains any changes:

  model.document.on( 'change', () => {
      if ( model.document.differ.getChanges().length > 0 ) {
          console.log( 'The Document has changed!' );
      }
  } );

最后一个代码片段在实现自动保存等功能时很有用。

首先,我看到您正在使用 Observable.fromEvent,它似乎是 RxJS 的一部分,并且与 jQuery 事件一起使用。 CKEditor 5 不使用 RxJS 也不 jQuery。它使用 custom events and custom observables,这与您要使用的可观察对象不同。

所以请注意:

Observable.fromEvent(this.editor.editing.view, 'selectionChangeDone');

不是监听事件的正确方式,很可能只是因为一些 duck typing.

监听CKE5事件的正确方式是:

this.editor.editing.view.on( 'selectionChangeDone', () => { /*...*/ } );

其次,'input'不是事件而是命令。如果你想听这个命令执行,你可以这样做:

this.editor.commands.get( 'input' ).on( 'execute', ( evt, args ) => {
    console.log( evt, args );
} );

不过这是一个很新鲜的API,会在ckeditor-core(0.9.0)的下个版本中引入,所以需要使用当前的master分支才能使用.