开发者

jQuery plugin - too many callbacks being returned

I have developed a jQuery plugin which does the job of showing and hiding content with a two sequenced animations. I am happy with the behaviour of the plugin when used on a single element, however when there are two elements on the page with the same class name used in the plugin call I get four callbacks being returned. It would seem that the plugin is not quite right and I would appreciate any hints or help that could get me closer to finishing this plugin.

I am keen to improve the quality of my code and would also appreciate any general feedback.

A working example of the plugin can be found here: http://jsfiddle.net/nijk/sVu7h/

The plugin code is as follows:

(function($){
$.fn.showHide = function(method, duration, options, callback){
    //console.log(method, duration, options, callback);
    var animating = false;
    var defaults = {
        $elem: this,
        easing: "swing"
    }
    var _sh = this;
    var init = function(){ 
            _sh.method = method;
            if("show" !== _sh.method && "hide" !== _sh.method){
                _sh.method = "show";
            }
            if( duration < 0 || (typeof(duration) == "string" && ("slow" !== duration && "normal" !== duration && "fast" !== duration) ) ){
                duration = "normal";
            }
            console.log( duration, typeof(duration) );
            if(typeof(options) == "function"){
                callback = options;
                options = {};
            }
            _sh.config = $.extend({}, defaults, options);
        if(!animating){
            //return _sh.each(function(index){
                //console.log("found element number: " + (index + 1));
                eval(_sh.method)();            
            //});
        }
    }
    var show = function(){
        animating = true;
        _sh.config.$elem.wrap('<div class="show-hide"/>').parent().hide();
        _sh.config.$elem.css({"opacity":0, "display":"block"});
        console.log("element height:",  _sh.config.$elem.parent().outerHeight());
        _sh.config.$elem.parent().slideDown(duration, _sh.config.easing, function(){
            _sh.config.$elem.animate({"opacity": 1}, duration, _sh.config.easing, function(){
                    console.log("show final cleanup called");
                    _sh.config.$elem.addClass("visible").unwrap();
                    $.isFunction(callback) && callback();
                    animating = false;
            });
        });
    };
    var hide = function(){
        animating = true;
        _sh.config.$elem.wrap('<div class="show-hide"/>');
        _sh.config.$elem.animate({"opacity":0}, duration, _sh.config.easing, function(){
            _sh.config.$elem.slideUp(duration, _sh.config.easing, function(){
                console.log("hide final cleanup called");
                _sh.config.$elem.removeClass("visible").hide().unwrap();
                $.isFunction(callback) && callback();
                animating = false;
            });
        });
    }
    init();
    return this;
}
})(jQuery);

@david.mchonechase: Thank you very much for your explanation and the code example.

I have made some tweeks on the callbacks so that the correct context for 'this' is returned. Any suggestions to improve to code would be greatly appreciated.

Working code updated here: http://jsfiddle.net/nijk/sVu7h/ and as follows:

(function($){
  $.fn.showHide = function(method, duration, options, callback){
    var animating = false;
    var defaults = { easing: "swing" };
    var _sh = this;
    _sh.method = show;

    if("hide" === method){
        _sh.method = hide;
    }
    if( duration < 0 || (typeof(duration) == "string" && ("slow" !== duration && "normal" !== duration && "fast" !== duration) ) ){
        duration = "normal";
    }
    if(typeof(options) == "function"){
        callback = options;
        options = {};
    }
    _sh.config = $.extend({}, defaults, options);

    function show(elem){
        animating = true;
        elem.wrap('<div class="show-hide"/>').parent().hide();
        elem.css({"opacity":0, "display":"block"});
        elem.parent().slideDown(duration, _sh.config.easing, function(){
            elem.animate({"opacity": 1}, duration, 开发者_StackOverflow中文版_sh.config.easing, function(){
                    elem.addClass("visible").unwrap();
                    $.isFunction(callback) && callback.call(this);
                    animating = false;
            });
        });
    };
    function hide(elem){
        animating = true;
        elem.wrap('<div class="show-hide"/>');
        elem.animate({"opacity":0}, duration, _sh.config.easing, function(){
            elem.slideUp(duration, _sh.config.easing, function(){
                elem.removeClass("visible").hide().unwrap();
                    $.isFunction(callback) && callback.call(this);
                    animating = false;
            });
        });
    };

    if(!animating){
        // loop through each element returned by jQuery selector
        return this.each(function(){
            _sh.method($(this));
        });
    }
  }
})(jQuery);


The problem is the mixture of global variables and the parent() call. The _sh.$elem variable contains two elements (one per jQuery selector result). The _sh.config.$elem.parent().slideDown call in the show function is called twice. Once complete, it then runs _sh.config.$elem.animate once per "showMe" element. So, the parent().slideDown is called twice, which then calls _sh.config.$elem.animate twice.

I usually try avoid global variables within jQuery plug-ins for functions like your show and hide, but the critical part is elements. (The animating global variable makes sense, though.)

I think something like this would work:

(function($){
    $.fn.showHide = function(method, duration, options, callback){
        //console.log(method, duration, options, callback);
        var animating = false;
        var defaults = {
            //$elem: this,
            easing: "swing"
        }
        var _sh = this;
        var init = function(){ 
            var methodFn = show; // reference actual function instead of string, since eval is evil (usually)
            if("hide" === method){
                methodFn = hide;
            }
            if( duration < 0 || (typeof(duration) == "string" && ("slow" !== duration && "normal" !== duration && "fast" !== duration) ) ){
                duration = "normal";
            }
            console.log( duration, typeof(duration) );
            if(typeof(options) == "function"){
                callback = options;
                options = {};
            }
            _sh.config = $.extend({}, defaults, options);
            if(!animating){
                // loop through each element returned by jQuery selector
                _sh.each(function(){ 
                    methodFn($(this)); // pass the single element to the show or hide functions
                });
            }
        }
        var show = function(elem){
            animating = true;
            elem.wrap('<div class="show-hide"/>').parent().hide();
            elem.css({"opacity":0, "display":"block"});
            console.log("element height:",  elem.parent().outerHeight());
            elem.parent().slideDown(duration, _sh.config.easing, function(){
                elem.animate({"opacity": 1}, duration, _sh.config.easing, function(){
                        console.log("show final cleanup called");
                        elem.addClass("visible").unwrap();
                        $.isFunction(callback) && callback();
                        animating = false;
                });
            });
        };
        var hide = function(elem){
            animating = true;
            elem.wrap('<div class="show-hide"/>');
            elem.animate({"opacity":0}, duration, _sh.config.easing, function(){
                elem.slideUp(duration, _sh.config.easing, function(){
                    console.log("hide final cleanup called");
                    elem.removeClass("visible").hide().unwrap();
                    $.isFunction(callback) && callback();
                    animating = false;
                });
            });
        }

        init();
        return this;
    }
})(jQuery);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜