Skip to content

怎样封装自己的jQuery插件 #2

Description

@superbug

xcat png pagespeed ic wu4z82ve52

前言

jQuery生态圈有各种各样的插件,极大地方便了前端开发者的开发效率。很多时候你需要一个图表插件、树控件、slide幻灯......诸如此类的插件,你可能会不假思索地打开github,然后就会出来一大堆你想要的jQuery控件,非常省事。然而,面对千奇百怪的业务需求,总有插件无法满足的时候,这时候我们需要写一个维护性高的jQuery插件,所以,下面就说下怎么去封装一个属于自己的jQuery插件。

基本原理

扩展jQuery原型链,像。。。这样:

$.fn.myPlugin = function() {
    console.log('Hello world!');
}

于是乎,所有jQuery对象都拥有了myPlugin方法,在你想要的时候,可以:

$('body').myPlugin();

太简单了,没感觉?来看一个通用的**jQuery插件封装模版**

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

它大概干了以下几件事

  • 实例化插件对象并暂存
  • 解析调用时传过来的参数,根据参数的不同做出不同的响应
  • 初始化(构造方法)
  • 。。。

这就意味着每写一个插件,就必须很无聊地重复地写以上的代码,当然如果只是为了单独写一两个插件,按上面的写法完全可以,也是业界比较推荐的最佳实践。然而,当我们的控件达到一定数量的时候就有必要有更好的组织代码的方式了。

jQuery widget

jquery widget就是一种很好的ui组件库很好的基础,jquery ui就是基于它构建出来的,它是jquery官方维护的一套插件组建方式,比较适合构建大规模的ui组件库。

jQuery widget封装模版

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

    //定义插件命名空间
    $.widget('namespace.widgetname', {
        //Options to be used as defaults
        options: {
            someValue: null
        },

        //插件实例化时调用
        _create: function() {

        },

        //插件销毁时调用
        destroy: function() {
            $.Widget.prototype.destroy.call(this);
        },

        //自定义方法
        methodB: function(event) {
            this._trigger('methodA', event, {
                key: value
            });
        },

        //自定义方法
        methodA: function(event) {
            this._trigger('dataChanged', event, {
                key: value
            });
        },

        //调整参数时调用
        _setOption: function(key, value) {
            switch (key) {
                case 'someValue':
                    //this.options.someValue = doSomethingWith(value);
                break;
                default:
                    //this.options[ key ] = value;
                break;
            }
            $.Widget.prototype._setOption.apply(this, arguments);
        }
    });
})(jQuery, window, document);

这样,我们就不用每次机械地去:

定义this.element

this.element = element;

解析options参数

this.options = $.extend({}, defaults, options);

实例化插件对象

if (!$.data(this, 'plugin_' + pluginName)) {
    $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
}

调用初始化|销毁方法

this.init();

所有这一切都是jquery widget自动帮你搞定的,是不是略high?

参考资源

javascript-patterns
why-use-the-widget-factory
how-to-use-the-widget-factory

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions