jQuery插件结构

时间:2011-06-07 09:54:18

标签: jquery jquery-plugins

我一直在研究我的jQuery Modal插件已经有一段时间了,我终于让它运行得很好 - 但是,我想知道我的插件结构和jQuery代码是否编码良好。如果我不确定我的代码是否完全最优,我是那种在晚上睡觉时遇到问题的人:)

非常感谢任何改进/反馈!

(function($) {

var methods = {
    init: function(options) {

        return this.each(function() {

            if (options) $.extend({}, settings, options);

            var $this = $(this),
                $title = $this.attr('title'),
                $href = $($this.attr('href'));

            $this.bind('click', function() {
                openWindow();
                return false;
            });

            $this.bind('open.iModal', function() { settings.onOpen() });
            $this.bind('loaded.iModal', function() { settings.onLoaded() });
            $this.bind('closed.iModal', function() { settings.onClose() });

            var openWindow = function() {
                $('body').append('<div id="iModalOverlay"></div><div id="iModalWrapper"><div id="iModalWindow"><div id="iModalLoading"></div><div id="iModalContent"><h4 class="inputBox">' + $title + '</h4></div></div><div id="iModalClose">X</div></div>');

                $this.trigger('open.iModal');
                $(this).iModal('resize');

                if (settings.closeOnClick) {
                    $('#iModalOverlay').click(function() {
                        $(this).iModal('close');
                        return false;                       
                    });
                }

                $('#iModalClose').click(function() {
                    $(this).iModal('close');
                    return false;                                   
                });

                $(window).resize(function() {
                    $(this).iModal('resize');
                });

                addContent();
            }

            var addContent = function() {
                $('#iModalContent').hide();
                $('#iModalLoading').show();

                var type = /\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(\.*))?$/i.test($this.attr('href')) ? 'image' : ($this.attr('href').indexOf('#') === 0) ? 'html' : 'ajax';

                switch(type) {
                    case 'html': 
                        $('#iModalContent').append($href);
                        break;

                    case 'ajax': 
                        $.get("/Testing/ajax/getfile.php", { file: $href }, function(data){
                            $('#iModalContent').html(data);
                        });
                        break;

                    case 'image':
                        $('#iModalContent').css('padding', 0);
                        $('#iModalWrapper').css('padding-bottom', '2px');

                        var img = new Image();
                        $(img).load(function() {
                            $('#iModalContent').append(this);
                        }).attr('src', $this.attr('href'));
                        break;
                }
                $('#iModalContent').show();
                $('#iModalLoading').hide();
                $(this).iModal('resize');

                if ($('#iModalContent input').length != 0) $('#iModalContent input').focus();

                $this.trigger('open.iModal');
            }
        });
    },

    close: function() {

        return this.each(function() {

            var $this = $(this),
                $href = $($this.attr('href'));

            $('#modalBoxes').append($href);
            $('#iModalOverlay, #iModalWrapper').remove();
            $this.trigger('closed.iModal');
            $this.unbind('.iModal');
        });
    },

    resize: function() {

        $('#iModalOverlay').css({
            height: $(window).height() + $(window).scrollTop(),
            width: $(window).width() + $(window).scrollLeft()
        });

        $('#iModalWrapper').css({
            top: ($(window).height() - $('#iModalWrapper').outerHeight()) / 2 + $(window).scrollTop(),
            left: ($(window).width() - $('#iModalWrapper').outerWidth()) / 2 + $(window).scrollLeft()
        });
    }
}

$.fn.iModal = function(method, options) {  

    settings = {
        onOpen: function() {},
        onLoaded: function() {},
        onClose: function() {},
        closeOnClick: true,
        title: false
    }

    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);

我知道它很长(好吧,它大约是其他模态插件大小的十分之一) - 所以我添加了一个TL; DR代码如下:

(function($) {

var methods = {
            // PUBLIC FUNCTIONS
    init: function(options) {

        return this.each(function() {

            if (options) $.extend({}, settings, options);

            var $this = $(this),
                $title = $this.attr('title'),
                $href = $($this.attr('href'));

            // PRIVATE FUNCTIONS
            var openWindow = function() {
                                    $this.trigger('open.iModal');
                addContent();
            }

            var addContent = function() {
                                $this.trigger('loaded.iModal');
            }
        });
    },

    close: function() {

        return this.each(function() {

            var $this = $(this),
                $href = $($this.attr('href'));

                            $this.trigger('closed.iModal');
            $this.unbind('.iModal');
        });
    },

    resize: function() {
    }
}

$.fn.iModal = function(method, options) {  

    settings = {
        onOpen: function() {},
        onLoaded: function() {},
        onClose: function() {},
        closeOnClick: true,
        title: false
    }

    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);

另外,正如你所看到的,我必须在我的init()和close()函数中定义$ this和$ href,我可以在任何地方定义我的私有变量并从任何地方访问它们吗?我听说过使用data()标签,但不知道它是如何工作的。

提前致谢:)

1 个答案:

答案 0 :(得分:1)

它看起来很不错,但我会避免在插件中对任何ID进行硬编码。您可以选择在设置对象中设置默认值,并允许用户覆盖该值,或者例如对所有ID使用前缀。

文献: