关于jQuery插件封装的总结

一、静态方法和扩展插件(类级别组件和对象级别组件)

  1、即是给jQuery命名空间下添加新的全局函数,也称为静态方法。如$.Ajax()$.extend()就是采用的类级别组件开发;

jQuery.pluginName = function() {

    // code

};

  2、对象级别的组件开发指的是直接在jQuery原型上挂载的方法,这样可以通过选择器获取的jQuery对象实例也能共享改方法,称为动态方法;

$.fn.pluginName = function() {

    // code

};

  3、考虑到环境的完整例子;通过闭包将jQuery对象传入。

(function ($) {
    $.fn.m​​yPlugin = function () {

        //此处没有必要将this包在$号中如$(this),因为this已经是一个jQuery对象。
        //$(this)等同于 $($('#element'));

        this.fadeIn('normal', function () {

            //此处callback函数中this关键字代表一个DOM元素

        });

    };
})(jQuery);

$('#element').myPlugin();

二、维护Chainability

  1、维护Chainability指的是维护通过返回this关键字,从而维护链式调用的写法。

(function ($) {

    $.fn.lockDimensions = function (type) {

        return this.each(function () {
       //这里面写什么不重要,重要的是,return this返回的jquery dom对象维护了后面调用时还能继续调用jq的其他方法,如:css()方法
            var $this = $(this);

            if (!type || type == 'width') {
                $this.width($this.width());
            }

            if (!type || type == 'height') {
                $this.height($this.height());
            }

        });

    };
})(jQuery);

$('div').lockDimensions('width').css('color', 'red');

三、设置默认值

  1、设置默认值指的是对于比较复杂的和提供了许多选项可定制的的插件,最好有一个当插件被调用的时候可以被拓展的默认设置(通过使用$.extend)。 因此,相对于调用一个有大量参数的插件,你可以调用一个对象参数,包含你了你想覆写的设置。

(function ($) {

    $.fn.tooltip = function (options) {

        //创建一些默认值,拓展任何被提供的选项
        var settings = $.extend({
            'location': 'top',
            'background-color': 'blue'
        }, options);

        return this.each(function () {

            // Tooltip插件代码

        });

    };
})(jQuery);

$('div').tooltip({
    'location': 'left'
});

四、命名空间与插件方法

  1、命名空间与固定方法:正确命名空间你的插件是插件开发的一个非常重要的一部分。 正确的命名空间,可以保证你的插件将有一个非常低的机会被其他插件或同一页上的其他代码覆盖。 命名空间也使得你的生活作为一个插件开发人员更容易,因为它可以帮助你更好地跟踪你的方法,事件和数据。

(function ($) {

    var methods = {
        init: function (options) {
            // this
        },
        show: function () {
            // is
        },
        hide: function () {
            // good
        },
        update: function (content) {
            // !!!
        }
    };

    $.fn.tooltip = function (method) {

        // 方法调用
        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.tooltip');
        }

    };

})(jQuery);

//调用init方法
$('div').tooltip();

//调用init方法
$('div').tooltip({
    foo: 'bar'
});

// 调用hide方法
$('div').tooltip('hide');

//调用Update方法
$('div').tooltip('update', 'This is the new tooltip content!');

这里通过传入方法名字符串及参数,从而调用它们

五、总结

  • 不要冗余包裹this关键字在插件的功能范围内。
  • 除非插件返回特定值,否则总是返回this关键字来维持chainability 。
  • 传递一个可拓展的默认对象参数而不是大量的参数给插件。
  • 不要在一个插件中多次命名不同方法。
  • 始终命名空间的方法,事件和数据。
原文地址:https://www.cnblogs.com/helloNico/p/11263651.html