jQuery插件编写设计模式

jquery 插件编写规范

将window, document写在闭包中,形成了局部变量,这样可以加快解析过程

;(function($, window, document, undefined) {

// 定义插件名字
var pluginName = 'bearDialog';

// 设置默认配置项
var defaults = {
    width: 200,
    height: 200,
    title: '提示'
}

// 真正的插件构造函数
function Dialog(el, opt) {

    // 获取调用插件的dom
    this.el = el; // 获取原生dom
    this.$el = $(el); // 获取jquery包装对象
    // 使用mixin模式扩展默认配置参数
    this.opt = $.extend({}, defaults, opt);
    this.pluginName = pluginName;

    this.init();

}

Dialog.prototype.init = function() {
    // 对话框初始化函数
    console.log(this.el);
    console.log(this.$el);
    console.log(this.opt);
}

// 初始化的时候,真正的扩展插件
$.fn[pluginName] = function(options) {

    // 针对一个dom的调用只生成一个实例
    $(this).each(function(idx, ele) {

        // $.data可以给任何对象绑定数据,并且该数据是存在内存中的,而不是单纯的dom上的data属性
        if (!$.data(ele, 'plugin_' + pluginName)) {

            $.data(ele, 'plugin_' + pluginName, pluginName);
            new Dialog(ele, options);

        }

    });
  }
})(jQuery, window, document);

你可能感兴趣的:(jQuery插件编写设计模式)