jQuery 方法封装(二)

转自:https://www.jianshu.com/p/5196cb659fb6

推荐看原文,此处只是记录下

概述

最近在慕课网上学习奇舞团课程系列--全屏切换效果的视频课程,在学到如何实现jQuery插件框架中,学到了封装jQuery插件的方法和基本的框架结构,将学习到的知识点整理在本文中,便于以后参考;

如何编写jQuery框架

闭包


// 立刻执行函数

(function($){

    // code

})(jQuery);

参数说明

形参: $

实参: jQuery

闭包的作用

  • 避免全局依赖

  • 避免第三方破坏

  • 兼容jQuery操作符'$'和jQuery;

开发方式

类级别组件开发

即是给jQuery命名空间下添加新的全局函数,也称为静态方法;

代码结构如下


jQuery.pluginName = function() {

    // code

};

例如:$.Ajax(), $.extend()就是采用的类级别组件开发;

对象级别组件开发

即是挂在jQuery原型下的方法,这样通过选择器获取的jQuery对象实例也能共享改方法,称为动态方法;

代码结构如下:


$.fn.pluginName = function() {

    // code

};

其中:


    $.fn === $.prototype;

例如:addClass(),attr()等方法,需要创建实例来调用这些方法;

链式调用


// 例子

$('div').next().addClass()...

$.fn.plugin = function() {

    return this.each(function() {

    // code

    })

}

代码说明

return this: 返回当前对象,来维护插件的链式调用;

each: 循环实现每个元素的访问;

单例模式

创建对象的实例,存在单例模式;


$.fn.pluginName = function() {

    var me = $(this),

    instance = me.data('pluginName');

    if (!instance) {

        me.data("pluginName", (instance = new pluginName()));

    }

}

说明:

如果实例存在,则不再重新创建;

利用data方法来存放插件对象的实例;

jQuery框架基本结构

利用闭包创建一个自执行的函数

(function($) {
  // code
})(jQuery);

定义插件对象

var pluginName = (function() {
// code
// 返回插件对象
return pluginName ;
  
})();

在插件对象的原型链上定义用户配置项

$.fn.pluginName.defaults = {
  optionName: value
  ...
}; 

创建插件的实例对象

$.fn.pluginName = function() {
// 实现链式调用
 return this.each(function(options) {
    // 缓存this对象
    var me = this;
    var instance = me.data('pluginName');
   // 判断实例是否存在,不存在则创建对象,并将该对象及配置项传入
    if (!instance) {
         instance = new pluginName(me, options);
          // 存放实例
          me.data('pluginName', instance)
     }
    // 在外部可以通过$(selection).pageSwitch("init")
    if ($.type(options) === "String") {
                return instance[options]();
            }
    });
};

给对象添加属性和方法,及初始化插件

function pluginName(element, options) {
  // 深拷贝,合并对象
  this.settings = $.extend(true, $.fn.pluginName.defaults, options || []);
this.element = element;
// 初始化插件
this.init();
}

在插件的原型上定义方法,以便实例可以调用

pluginName.prototype = { fnName: function() {} };

案例代码


(function($) {

    // 私有方法

    var privateFun = function() {};

    // 合并对象等

    var pageSwitch = (function() {

        function pageSwitch(element, options) {

            // 设置为true深拷贝,合并对象

            this.settings = $.extend(true, $.fn.pageSwitch.default, options || {});

            this.element = element;

            // 初始化插件

            this.init()

        }

        // 在pageSwitch原型上定义方法,让实例可以调用这些方法

        pageSwitch.prototype = {

            // 功能方法

            init: function() {}

        };

        return pageSwitch;

    })();

    // 创建对象实例

    $.fn.pageSwitch = function(options) {

        // 实现链式调用

        return this.each(function() {

            var me = $(this),

                instance = me.data("pageSwitch");

            // 判断实例是否存在,不存在则创建对象,并将该对象及配置项传入

            if (!instance) {

                instance = new pageSwitch(me, options);

                // 存放实例

                me.data("pageSwitch", instance);

            }

            // 在外部可以通过$(selection).pageSwitch("init")

            if ($.type(options) === "String" || $.type(options) === "string") {

                return instance[options]();

            }

        });

    };

    // 配置参数

    $.fn.pageSwitch.default = {

        // 选择器

        selectors: {

            // 父层容器

            sections: '.sections',

            // 页面容器

            section: '.section',

            // 分页容器

            page: '.pages',

            // 分页选中时的高亮效果

            active: '.active'

        },

        // 页面开始的索引值

        index: 0,

        // 动画的效果

        easing: 'ease',

        // 动画执行的时间

        duration: 500,

        // 页面是否循环播放

        loop: false,

        // 是否进行分页处理

        pagination: true,

        // 是否触发键盘事件

        kerboard: true,

        // 全屏方向,横屏,竖屏

        direction: 'vertical',

        // 实现滑屏动画后执行的回调函数

        callback: ""

    };

    // 在插件内部初始化,但是这种写法需要在目标元素上添加data-pageSwitch

     $(function() {

        $("[data-pageSwitch]").pageSwitch();

    }) 

})(jQuery)

插件的初始化

外部初始化


<script>

$("#container").pageSwitch("init")

</script>

使用data-*

在目标元素上添加data-*属性,来初始化;

<div id="container" data-pageSwitch>
        <div class="sections">
            <div class="section" id="section0">
            </div>
            <div class="section" id="section1">
            </div>
            <div class="section" id="section2">
            </div>
            <div class="section" id="section3">
            </div>
        </div>
    </div>
原文地址:https://www.cnblogs.com/PrintY/p/13501658.html