CKEditor: HowTo destroy instance on blur?

2020-07-29 17:29发布

问题:

i have a single html page with mulitple div elements on it. Each time a user clicks on on a div, it is replaced with an CKEditor on the fly:

$('.editable').click(function() {
    editor = CKEDITOR.replace(this);
});

Now, if the CKEditor instance loses its focus (blur event), i need to post the content to a separate script via ajax (if something changed) and destroy this instance:

$('.editable').click(function() {
    editor = CKEDITOR.replace(this);
    editor.on('blur', function(e)
    {
        if (e.editor.checkDirty())
           // get data with e.editor.getData() and do some ajax magic 

        e.editor.destroy();
    });
});

But this example won't work because, i don't know why, destory() will be called before checkDirty(). How can i get this working?

回答1:

How about if you put the destroy() inside the if() statement? You could have an else clause that invokes destroy if nothing has changed. If something has changed, you can invoke destroy() within the if clause once the data has been transfered.

$('.editable').click(function() {
  editor = CKEDITOR.replace(this);
  editor.on('blur', function(e)
  {
    if (e.editor.checkDirty()) {
       // get data with e.editor.getData() and do some ajax magic
       if ( dataTransferComplete ) {
         e.editor.destroy();
       }

     } else {
       e.editor.destroy();
     }
  });
});

Or you could check a variable before invoking destroy(). Set that variable to true after the data transfer has been completed and in the else clause, that way destroy() won't be invoked until you've checked for changes and transfered any updated data.

$('.editable').click(function() {
  editor = CKEDITOR.replace(this);
  editor.on('blur', function(e)
  {
    var okToDestroy = false;

    if (e.editor.checkDirty()) {
       // get data with e.editor.getData() and do some ajax magic
       okToDestroy = true;
     } else {
       okToDestroy = true;
     }

    if (okToDestroy )
      e.editor.destroy();

  });
});

This is an outline, I haven't tested the code, but if shows the concept.

Be Well,
Joe