简体   繁体   中英

jQuery - Callback failing if there is no options parameter

I'm attempting to build a simple plugin like this

(function($) {

        $.fn.gpSlideOut = function(options, callback) {

            // default options - these are used when no others are specified
            $.fn.gpSlideOut.defaults = {
            fadeToColour: "#ffffb3",
            fadeToColourSpeed: 500,
            slideUpSpeed: 400
            };

        // build main options before element iteration
            var o = $.extend({}, $.fn.gpSlideOut.defaults, options);

             this.each(function() {
                $(this)
                .animate({backgroundColor: o.fadeToColour},o.fadeToColourSpeed)
                .slideUp(o.SlideUpSpeed, function(){
                    if (typeof callback == 'function') {  // make sure the callback is a function
                        callback.call(this);  // brings the scope to the callback
                    }
                });

                });

            return this;

        };

        //  invoke the function we just created passing it the jQuery object
    })(jQuery);

The confusion I'm having is that normally on jQuery plugins you can call something like this:

$(this_moveable_item).gpSlideOut(function() {
                // Do stuff
            });

Without the options parameter, but it misses the callback if I do it like that so I have to always have

var options = {}
$(this_moveable_item).gpSlideOut(options, function() {
                    // Do stuff
                }); 

Even if I only want to use the defaults.

Is there anyway to make sure the callback function is called whether or not the options parameter is there?

Cheers.

//you have no second parameter
if (callback == undefined)
   ...

//have a function
if ($.isFunction(options))
  ...

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