这是一个很好的方式来建立一个插件

Is this way a good one to build a plugin?

本文关键字:一个 建立 插件 方式 很好      更新时间:2023-09-26

我只是想知道以下方法是否是构建jQuery插件的好方法,如果不是,哪些是最佳实践:

$.fn.loginsys = function(options) {
    var opts = $.extend({}, $.fn.loginsys.defaults, options);
    return this.each(function() {
        /* Code To Be Executed */
    });
}
$.fn.loginsys.defaults = {
    /* Some Options */
}
(function( $ ) {
  $.fn.myPlugin = function() {
    // Do your awesome plugin stuff here
  };
})( jQuery );

更多信息请点击此处:http://docs.jquery.com/Plugins/Authoring

抛开最佳实践和一切不谈,是否有理由公开默认值?

如果你想让它们从外部进行编辑,你可能需要公开一个setter,并将它们保存在$.fn.loginsys=函数闭包中,以确保它们不会被篡改,从而阻止你的插件工作。

例如,请参阅jQuery的ajaxSettings()。

我想你只是缺少包装

(function($) {
    // plugin code here
})(jQuery);

但是,有很多插件模式;这里有一堆可供下载的模板。

我将从jquery教程插件中建议(但有几种方法):

(function($) 
{   
    var globalSettings=
    {
        width:400,
        height:400
    };
    var methods =
    {
        init : function(options)
        {
            return this.each(function() 
            {
                var $this=$(this);
                var settings=$.extend({}, globalSettings, options);
                //your code
            });
        },
        destroy : function()
        {
            return this.each(function()
            {
            });
        },
        option : function(option, value)
        {
            if(value!=null && value!=undefined)
            {
                return this.each(function(){
                    var $this=$(this);
                    var curr_setts=$this.data('settings');
                    curr_setts[option]=value;
                    $this.data('settings',curr_setts);
                });
            }
            else
            {
                var $this=$(this);
                var curr_setts=$this.data('settings');
                return curr_setts[option];
            }
        }
    };
    $.fn.siter=function(method, options) 
    {
        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 on jQuery');
        }
    };
})(jQuery);

关于如何编写jQuery插件,有一些很好的教程,比如http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/.只要谷歌一下。另外,看看其他jQuery插件是如何构建的。我认为这是你能学到最多的地方。