Search code examples
javascriptjqueryhtmlckeditortextarea

Cannot get instance of CKEditor


I have several fields which need to be initialized with CKEditor, for this I have created an helper class that contains the initEditor method.

The method below should return the initialized editor but it doesn't:

window.CKEditorHelper = window.CKEditorHelper || {};

(function (exports) {

    exports.initEditor = function (input, myEditor) {
        ClassicEditor
            .create(document.querySelector(input), {
                language: {
                    ui: 'en'
                    content: 'en'
                }
            })
            .then(editor => {
                myEditor = editor;
            });
    };

})(window.CKEditorHelper);

this is called in the following way:

let editor = null;
CKEditorHelper.initEditor('#description', editor);

so when I click on a button:

$('#save').on('click', function(){
    console.log(editor.getData());
});

I get:

Cannot read property 'getData' of null

what I did wrong?


Solution

  • There are some issues on your code

    let editor = null;

    the let keyword only define a variable within function scope, when you use editor on another scope (your click handle event), it could be undefined

    Another line

    myEditor = editor;

    This just simple made the reference to your original editor object will gone

    Here is my solution to fix it

    Change the way you init an editor like bellow

    window.editorInstance = {editor: null};
    CKEditorHelper.initEditor('#description', editorInstance);
    

    Change your CKEditorHelper to

    window.CKEditorHelper = window.CKEditorHelper || {};
    
    (function (exports) {
    
    exports.initEditor = function (input, myEditorInstance) {
        ClassicEditor
            .create(document.querySelector(input), {
                language: {
                    ui: 'en'
                    content: 'en'
                }
            })
            .then(editor => {
                myEditorInstance.editor = editor;
            });
    };
    
    })(window.CKEditorHelper);
    

    And when you want to use your editor

    console.log(editorInstance.editor.getData());