简体   繁体   中英

Prevent function from being called immediately when passing arguments

I have the following code, which works

var settings = trumbowyg.o.plugins.giphycrumbs;
settings = $.extend(true, {},
    defaultOptions,
    trumbowyg.o.plugins.giphycrumbs || {}
);

if(!settings.open_modal) {
    settings.open_modal = function() {
        $(settings.modal_selector).modal('show');
    }
}

trumbowyg.addBtnDef('giphycrumbs', {
    fn: settings.open_modal
});

Where settings.open_modal is executed when a button is pressed.

However, I want to define this function elsewhere (In the plugins section of trumbowyg instead of inside the plugin itself), but to do that, I need to be able to pass a selector to it. I've already done this with a similar close_modal function, but I'm having issues with the open_modal function.

Here is how I would define the function the way I want to:

plugins: {
    giphycrumbs: {
        ...
        modal_selector: '#giphy_modal',
        close_modal: function(selector) {
            $(selector).modal('hide');
        },
        open_modal: function(selector) {
            $(selector).modal('show');
        }
    },
}

This would mean that my addBtnDef call would be changed to something like:

trumbowyg.addBtnDef('giphycrumbs', {
    fn: settings.open_modal(settings.modal_selector)
});

However, this causes the function to be ran immediately upon initialization instead of waiting for the button to be pressed as it did before I added the selector to the function.

How can I make this code wait for the button to be pressed before running the function, like it did before I added the selector?

This is one way to fix this, though I'd prefer a better solution which doesn't require an extra function to work.

First, declare settings outside of the plugin init, and assign the settings to it the same way as before.

var settings = null;

...

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

Next, create a new function which does not use any arguments which just calls settings.open_modal(settings.modal_selector) .

function run_open_modal() {
    settings.open_modal(settings.modal_selector);
}

And call that function in the addBtnDef call.

trumbowyg.addBtnDef('giphycrumbs', {
    fn: run_open_modal
});

is open_modal declared beforehand? Because, if it isn't, you could declare the settings as:

 if(!settings.open_modal) {
 settings.open_modal = function(selector) {
    selector= selector||settings.modal_selector.
      $(selector).modal('show');
   }
} 

So in case you can redefine it, make the orginal closure accept a selector. If you don't pass one, then it defaults to its initial behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM