CKEditor 5 how to get the click, update and deleted events from any widget/Model/View

2k views Asked by At

How can I get notified on a CKEditor 5 model, View and widget's click, update and delete events?

Let's assume that I have a custom plugin implementation similar to a link plugin or highlighter plugin. Now, how can I get the following events?

  • When user clicks on the link/highlighted element.
  • When user updates the inner content of the highlighted element.
  • When user removes the entire highlighted link or highlighter element from editor.

The element can be a model element/view element/or a widget.

1

There are 1 answers

0
MTilsted On

Here is the code I use. It need to be in the init() method for a plugin. I don't know if this is the correct way to do it, but it works for me(tm).

            const editor = this.editor;
            const model=editor.model;
            const editingView=editor.editing.view;
            editingView.addObserver( ClickObserver );
            const viewDocument = editor.editing.view.document;

            this.listenTo( viewDocument, 'click', (event,data) => {
                const target=data.target; // This is the view the user clicked on 
                const modelObj=editor.editing.mapper.toModelElement(target);
// modelObj is the model object for the element the user clicked on. Now you just need to test if clicking on this model is something you are interested in.    

    //          console.log(modelObj);
            } );

Note that this does seem to fail if you click on a AttributeElement (Such as bold text). In that case you can either call on the target.parent until you get a result.