jQuery插件开发前准备(四)

通过上面三个小结的梳理,最终来个总结,将插件通用形式整成模板,以供重复调用。

(function($) {
    var MyPlugin = (function() {
        function MyPlugin(element, options) {
            // 将用户配置项与默认选项进行深拷贝
            this.settings = $.extend(true, $.fn.MyPlugin.defaultValue, options || {});
            this.element = element;
            this.init();
        }
        MyPlugin.prototype = {
            // 初始化插件
            init: function() {
                var _this = this;
            },
            //绘制dom结构
            _initDom: function() {

            }
        };
        // 必须要将该对象返回出去
        return MyPlugin;
    })();
    $.fn.MyPlugin = function(options) {
        return this.each(function() {
            var _this = $(this),
                // 从当前对象下读取实例
                instance = _this.data('MyPlugin');
            // 如果没有实例新建一个
            if (!instance) {
                // 新建实例,_this表示当前选中元素,options表示配置
                instance = new MyPlugin(_this, options);
                // 将当前实例保存到data数据中
                _this.data('MyPlugin', instance);
            }
            if ($.type(options) === 'string') {
                return instance[options]();
            }
        });
    };
    // 默认参数
    $.fn.MyPlugin.defaultValue = {
        value1: '1',
        value2: '2',
        value3: '3',
        value4: '4'
    };
})(jQuery);        

 

posted @ 2016-08-17 22:16  宋小玉  阅读(253)  评论(0编辑  收藏  举报