z4none
12/15/2016 - 7:01 AM

jquery plugin template

jquery plugin template

;(function ($, window, document, undefined) {
    var pluginName = 'pluginName',  //自定义一个插件名称
        defaults = {                //定义插件的默认属性
        };

    function Plugin(element, options) {
        this.element = element;     //缓存element,让原型链上的方法都可以访问

        this.options = $.extend({}, defaults, options);  //默认属性和自定义熟悉合并处理

        this._defaults = defaults;
        this._name = pluginName;

        this.init();  //插件初始化(在里面可以做dom构造,事件绑定等操作)
    }

    Plugin.prototype.init = function() {
    };

    $.fn[pluginName] = function (options) {
        return this.each(function () {
            //将实例化后的插件暂存,避免重复渲染
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
            }
        });
    }

})(jQuery, window, document);