Search code examples
javascriptcodemirror

How to set a property of a function which is defined as a property, during declaration


JSFiddle in here, this is a JavaScript and/or CodeMirror question.

In the below snippet, hint function is defined as a property in hintOptions object.

Is there a possibility to set a property of that function, without defining it outside the code block?

var editor = CodeMirror.fromTextArea(myTextarea, {
    hintOptions: {
        hint: function(cm, callback, options) {
            return {
            }
        }
    }
});

I tried with anonymous function, as in:

var editor = CodeMirror.fromTextArea(myTextarea, {
    hintOptions: {
        hint: (function(cm, callback, options) {
            return {
            }
        })({
            async: true
        })
    }
});

but it seems to be a syntax error, since the JavaScript doesn't work at all.

As CodeMirror docs mention:

hint: function

A hinting function, as specified above. It is possible to set the async property on a hinting function to true, in which case it will be called with arguments (cm, callback, ?options)

To check if async is correctly set:

  1. Open the JSFiddle
  2. Click on the 'class code'
  3. Type Ctrl+Space
  4. The log textarea should have not undefined

Solution

  • An IIFE in the object initialiser to create a function with an async property seems to work:

    let testObj = {
        hintOptions: {
            hint:   (function () {
                let hint = function(cm, callback, options) {
                     log(options);
                     return {
                         from: cm.getDoc().getCursor(),
                         to: cm.getaDoc().getCursor(),
                         list: ['foo', 'bar']
                     }
                 }
                 hint.async = true;
                 return hint
            })()
        }
    };
    
    console.log("hint.async: " + testObj.hintOptions.hint.async);  

    I managed to get "[object Object]" in the fiddle following the post instructions but don't know it that is the expected result.