javascriptjquerytrumbowyg

Function stored to a variable not running when called


I'm working on a plugin for Trumbowyg where I'm trying to store a function in a variable so it can be called later but also be over-writable without altering the included javascript file.

The problem is, the function is not being called when I try to call it.

Here is my relevant code:

init: function (trumbowyg) {
    
    var plugins = trumbowyg.o.plugins;

    ...
    
    if(!plugins.giphycrumbs.close_modal) {
        plugins.giphycrumbs.close_modal = function() {
            console.log('close modal');
            $(plugins.giphycrumbs.modal_selector).modal('hide');
        }
    }
    
    $(document).on('click', '.add_giphy', function() {
        trumbowyg.execCmd('insertImage', $(this).attr('src'), false, true);
        
        plugins.giphycrumbs.close_modal;
        
    });
    
    // If the plugin is a button
    trumbowyg.addBtnDef('giphycrumbs', {
            //this function is handled exactly the same way except it actually works
        fn: plugins.giphycrumbs.open_modal
    });
}

In my code above, you can see I am checking if plugins.giphycrumbs.close_modal is NOT set, and if thats true, I set it to a function which is supposed to close a modal.

In my click handler for .add_giphy, the insertImage code works, but plugins.giphycrumbs.close_modal is never executed (I don't get the console.log message embedded in the function)

If I do console.log(plugins.giphycrumbs.close_modal) the expected function is put into the console.

Why is the close_modal function not executed in my code?


Solution

  • Answer

    Try adding parentheses to close_modal inside your click handler.

    Explanation

    It seems to me like you are not invoking (calling) this function.

    In your click handler, there's this line plugins.giphycrumbs.close_modal;

    In javascript, this is a reference to a property on the giphycrumbs object. Though it happens to be a function, it will not be invoked as such unless you use parentheses after it (and optionally give it some arguments).

    Hope that helps! 👍