sfarzoso
sfarzoso

Reputation: 1610

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?

Upvotes: 2

Views: 1283

Answers (2)

Vo Kim Nguyen
Vo Kim Nguyen

Reputation: 1643

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());

Upvotes: 4

Nijin P J
Nijin P J

Reputation: 1322

You can give this in javascript

$(document).ready(function () {
  CKEDITOR.replace('tmpcontent', { height: '100px' })
})

take the value by using following

$('#save').on('click', function(){
 var textareaValue = CKEDITOR.instances.tmpcontent.getData();
});
<label class="control-label">Message</label>
<textarea name="tmpcontent" id="tmpcontent" class="form-control"></textarea>

//OR in latest version

var myEditor;

ClassicEditor
    .create( document.querySelector( '#description' ) )
    .then( editor => {
        console.log( 'Editor was initialized', editor );
        myEditor = editor;
    } )
    .catch( err => {
        console.error( err.stack );
    } );

and then get data using

myEditor.getData();

Upvotes: 0

Related Questions