CKEDITOR.destroy() does not exist?! How to fix it on multiple CKEditor instance intialization ;) .

pcmagas

Dimitrios Desyllas

Posted on October 9, 2021

CKEDITOR.destroy() does not exist?! How to fix it on multiple CKEditor instance intialization ;) .

Sometimes you need multiple CKeditor instances in your web app. For example let suppose we have the following html and js:

<form action="#">
  <textarea id="one"></textarea>
  <textarea id="two"></textarea>
  <button type="submit">Submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode
$(document).ready(function(){
  let CKEDITOR=[]

  ClassicEditor.create(document.querySelector('#one')).then(editor => {
    CKEDITOR["one"] = editor;
  })

  ClassicEditor.create(document.querySelector('#two')).then(editor => {
    CKEDITOR["two"] = editor;
  })

  $("form").on('submit',function(e){
     e.preventDefault();

      CKEDITOR["one"].destroy();
      CKEDITOR["two"].destroy();

     //Ajax Call or rest of submission goes here
  });
})
Enter fullscreen mode Exit fullscreen mode

As you can see, we load 2 instances of CKeditor into 2 textareas. And we destroy them during submission. That can be rather troublesome in case we submit the form, because in either of one of these lines we may get the error:

CKEDITOR[...].destroy() function does not exist.
Enter fullscreen mode Exit fullscreen mode

This happens because CKEditor may not be finalized in its initialization before submit handler to the form provided, due to javascript's asynchronous nature.

We can bypass the problem like that:

$(document).ready(function(){
  let CKEDITOR=[]
  let intializeForm = () => {

   if(!CKEDITOR["one"] || !CKEDITOR["two"]){
     return;
   }

   $("form").on('submit',function(e){
     e.preventDefault();
     //Ajax Call goes here
      CKEDITOR["one"].destroy();
      CKEDITOR["two"].destroy();
    });
  }
  ClassicEditor.create(document.querySelector('#one')).then(editor => {
    CKEDITOR["one"] = editor;
    intializeForm()
  })

  ClassicEditor.create(document.querySelector('#two')).then(editor => {
    CKEDITOR["two"] = editor;
    intializeForm()
  })
})

Enter fullscreen mode Exit fullscreen mode

The main difference in the code above is that we place the form submit handler in the function intializeForm then on each CKEditor initialization we call it. This function checks if all CKeditor instances initialized, then places the event handler on form. This function is called upon on each CKeditor intialization, therefore the last editor initialized also initializes the form submission as well.

Is it a tip that can save you from unwanted mess on multiple CKeditor instances ;) .

💖 💪 🙅 🚩
pcmagas
Dimitrios Desyllas

Posted on October 9, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related