开发者

jQuery plugin script code layout and design

I have never written a jQuery plugin before but an working on one now. I'm struggling with how to include internal functions within it. Here's what I came up with (in an abbreviated format). 开发者_运维技巧 Does this make sense? It seems a little ... odd. Is there a better, cleaner way I could arrange this code?

(function($) {

$.myplugin = { version : '0.1a' }

$.fn.myplugin = function(options)
{
    // global vars
    var arrone = Array(),
        arrtwo = Array();

    $.myplugin.defaults = {
        doctor : 'seuss',
        jim : 'hensen'
    }

    $.myplugin.variable = null;

    $.myplugin.go = function()
    {
    // do stuff
    $('.myclass').click(function() { $.myplugin.otherfunction(this); });
}

$.myplugin.otherfunction = function(object)
{
    // do more stuff
}

var opts = $.extend($.myplugin.default, options);

return $(this).each($.myplugin.go);

I'm missing a few brackets and braces here and there, that was typed quickly, but that's the general format. More or less, creating a Javascript object within the plugin function call.

Thanks for any help and insight, as always!


Here is a little plugin I wrote for my website. It is a gallery for jQuery

    (function($){
    var currentSlide = 0;
    var slides = new Array();
    var nav = new Array();
    var timer;
    var wait = 2200;        // Delay before changing slides
    var speed = 250;        // Speed at which slides fade
    var canChange = true;   // To prevent bugs between changing slides
    var methods = {
        init:function(options){
            $('.slide',this).each(function(){
                $(this).hide();
                slides[slides.length] = $(this);
            });
            $(this).append('<div class="slideshow-nav-container"></div>');
            for(var i=0;i<slides.length;i++){
                    $('.slideshow-nav-container',this).append('<a href="#" class="slideshow-nav">' + (i + 1) + '</a>');    
            }
            $('.slideshow-nav').each(function(key,value){
                nav[nav.length] = $(this);
                if(key == 0){
                    $(this).addClass('slideshow-nav-active');
                }
                $(this).click(function(){
                    $('.slideshow-nav').removeClass('slideshow-nav-active');
                    methods['set'].call(this,key);
                    $(this).addClass('slideshow-nav-active');
                    return false;
                });
            });
            methods['next'].call(this,true);
            return true;
        },
        next:function(init){
            if(init){
                methods['change'].call(this,currentSlide);
            }
            else{
                methods['change'].call(this,currentSlide + 1);
            }
            timer = setTimeout(
                function(){
                    methods['next'].call(this,false);
                },
                wait);
            return true;
        },
        set:function(slide){
            methods['change'].call(this,slide);
            clearTimeout(timer);
        },
        change:function(slide){
            if(canChange){
                canChange = false;
                $(slides[currentSlide]).fadeOut(speed,function(){
                    $(nav[currentSlide]).removeClass('slideshow-nav-active');
                    if(slide > slides.length - 1 || slide < 0){
                        slide = 0;
                    }
                    currentSlide = slide;
                    $(nav[currentSlide]).addClass('slideshow-nav-active');
                    $(slides[currentSlide]).fadeIn(speed);
                    canChange = true;
                    return true;
                });
            }
            return true;
        }
    };
    $.fn.slideshow = function(method){
        if(methods[method]){
            return methods[method].apply(this,Array.prototype.slice.call(arguments,1));
        }else if(typeof method === 'object' || !method){
            return methods.init.apply(this,arguments);
        }else{
            $.error('Method ' + method + ' does not exist!');
        }    
    };
})(jQuery);

Hopefully you should be able to look at this and tell how each function is called. If not, please comment on this and I will explain it further.


First of all, you're off to an excellent start. You need to wrap jQuery in a closure to prevent any namespacing conflicts, so the basis should always be this:

(function($) {
    // In here you can always safely use $ to refer to jQuery
})(jQuery);

Now we add the actual plugin and the default options, based on an established pattern. It looks like this.

(function($) {

    // A helper function
    function changeElem(elem, upperCase) {
        if (upperCase) {
            elem.html(elem.html().toUpperCase());
        }
    }

    // The plugin
    $.fn.demo = function(options) {
        var settings = $.extend({}, $.fn.demo.defaults, options);
        changeElem(this, settings.upperCase);
        return this.css(settings.css);
    };

    // The defaults, with 2 examples
    $.fn.demo.defaults = {
        css: { 'font-weight': 'bold' },
        upperCase: false
    };

})(jQuery);

$(".foo").demo({ upperCase: true });

I posted the full working code at http://www.jsfiddle.net/w8DTB/

P.S. This stuff and lots more can be found by googling for jquery plugin template or jquery plugin tutorial.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜