jQuery - Callback failing if there is no options parameter

Posted by user249950 on Stack Overflow See other posts from Stack Overflow or by user249950
Published on 2010-04-14T15:25:01Z Indexed on 2010/04/14 15:33 UTC
Read the original article Hit count: 354

Filed under:
|
|

Hi, 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.

© Stack Overflow or respective owner

Related posts about jquery-plugins

Related posts about jQuery