Home > Web Front-end > JS Tutorial > Standard writing method for jQuery plug-in development

Standard writing method for jQuery plug-in development

jacklove
Release: 2018-06-11 22:45:00
Original
1627 people have browsed it

Preface   

Nowadays, jquery is almost indispensable for web development. Even the VS artifact has built jquery and ui into web projects since the 2010 version. As for the benefits of using jquery, I won’t go into details here, everyone who has used it knows it. Today we will discuss the plug-in mechanism of jquery. jquery has thousands of third-party plug-ins. Sometimes we have written an independent function and want to combine it with jquery. We can use jquery chain call. This requires Extend jquery and write it in the form of a plug-in. For example, the following is a demo of simply extending the Jquery object:

        //sample:扩展jquery对象的方法,bold()用于加粗字体。
        (function ($) {
            $.fn.extend({
                "bold": function () {                    ///<summary>
                    /// 加粗字体
                    ///</summary>
                    return this.css({ fontWeight: "bold" });
                }
            });
        })(jQuery);
Copy after login

Calling method:

This is a very simple Extension. Next we analyze the above code step by step.

1. jquery’s plug-in mechanism

In order to facilitate users to create plug-ins, jquery provides jQuery.extend() and jQuery.fn.extend() methods.

1. The jQuery.extend() method has an overload.

jQuery.extend(object), one parameter is used to extend the jQuery class itself, which is used to add new functions to the jQuery class/namespace, or static methods, such as jQuery's built-in Ajax methods are all called using jQuery.ajax(), which is a bit like the "class name. method name" static method calling method. Let’s also write an example of jQuery.extend(object):


        //扩展jQuery对象本身
        jQuery.extend({
            "minValue": function (a, b) {                ///<summary>
                /// 比较两个值,返回最小值
                ///</summary>
                return a < b ? a : b;
            },
            "maxValue": function (a, b) {                ///<summary>
                /// 比较两个值,返回最大值
                ///</summary>
                return a > b ? a : b;
            }
        });        //调用
        var i = 100; j = 101;        var min_v = $.minValue(i, j); // min_v 等于 100
        var max_v = $.maxValue(i, j); // max_v 等于 101
Copy after login

Overloaded version: jQuery.extend([deep], target, object1, [objectN])

Extend an object with one or more other objects and return The object being extended.
If no target is specified, the jQuery namespace itself will be expanded. This helps plugin authors add new methods to jQuery.
If the first parameter is set to true, jQuery returns a deep copy, recursively copying any objects found. Otherwise, the copy will share the structure with the original object.
Undefined properties will not be copied, however properties inherited from the object's prototype will be copied.
Parameters
deep: Optional. If set to true, merge recursively.
target: The object to be modified.
object1: The object to be merged into the first object.
objectN: Optional. The object to be merged into the first object.
Example 1:
Merge settings and options, modify and return settings.

var settings = { validate: false, limit: 5, name: "foo" }; 
var options = { validate: true, name: "bar" }; 
jQuery.extend(settings, options);
Copy after login

Result: <br/>

settings == { validate: true, limit: 5, name: "bar" }
Copy after login

Example 2:
Merge defaults and options , do not modify defaults.

var empty = {}; 
var defaults = { validate: false, limit: 5, name: "foo" }; 
var options = { validate: true, name: "bar" }; 
var settings = jQuery.extend(empty, defaults, options);
结果:
settings == { validate: true, limit: 5, name: "bar" } 
empty == { validate: true, limit: 5, name: "bar" }
Copy after login

<br/>This overloaded method is generally used to override the default parameters of the plug-in with custom plug-in parameters when writing plug-ins.

jQuery.fn.extend(object) extends the jQuery element set to provide new methods (usually used to make plug-ins).

First of all, let’s take a look at what fn is. Looking at the jQuery code, it's not hard to find.

jQuery.fn = jQuery.prototype = {

  init: function( selector, context ) {.....};
};

Original jQuery .fn = jQuery.prototype, which is the prototype of the jQuery object. The jQuery.fn.extend() method is the prototype method of extending the jQuery object. We know that extending the method on the prototype is equivalent to adding a "member method" to the object. The "member method" of the class can only be called by the object of the class, so use the jQuery.fn.extend(object) extended method, an instance of the jQuery class You can use this "member function". The jQuery.fn.extend(object) and jQuery.extend(object) methods must be distinguished.

2. Self-executing anonymous function/closure

1. 什么是自执行的匿名函数?
   它是指形如这样的函数: (function {// code})();
2. 疑问 为什么(function {// code})();可以被执行, 而function {// code}();却会报错?
3. 分析
(1). 首先, 要清楚两者的区别: (function {// code})是表达式, function {// code}是函数声明.
(2). 其次, js"预编译"的特点: js在"预编译"阶段, 会解释函数声明, 但却会忽略表式.
(3). 当js执行到function() {//code}();时, 由于function() {//code}在"预编译"阶段已经被解释过, js会跳过function(){//code}, 试图去执行();, 故会报错;
当js执行到(function {// code})();时, 由于(function {// code})是表达式, js会去对它求解得到返回值, 由于返回值是一 个函数, 故而遇到();时, 便会被执行.

另外, 函数转换为表达式的方法并不一定要靠分组操作符(),我们还可以用void操作符,~操作符,!操作符……

例如:
bootstrap 框架中的插件写法:
!function($){
  //do something;
}(jQuery);


(function($){
  //do something;
})(jQuery); 是一回事。

匿名函数最大的用途是创建闭包(这是JavaScript语言的特性之一),并且还可以构建命名空间,以减少全局变量的使用。
例如:
var a=1;
(function()(){
    var a=100;
  })();
alert(a); //弹出 1
更多 闭包和匿名函数 可查看 Javascript的匿名函数与自执行 这篇文章。

三、一步一步封装JQuery插件

接下来我们一起来写个高亮的jqury插件
1.定一个闭包区域,防止插件"污染"


//闭包限定命名空间(function ($) {
    
})(window.jQuery);
Copy after login


2.jQuery.fn.extend(object)扩展jquery 方法,制作插件



//闭包限定命名空间(function ($) {
    $.fn.extend({
        "highLight":function(options){            //do something
        }
    });
})(window.jQuery);
Copy after login

3.给插件默认参数,实现 插件的功能

//闭包限定命名空间(function ($) {
    $.fn.extend({
        "highLight": function (options) {            var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆盖插件默认参数
            this.each(function () {  //这里的this 就是 jQuery对象
                //遍历所有的要高亮的dom,当调用 highLight()插件的是一个集合的时候。
                var $this = $(this); //获取当前dom 的 jQuery对象,这里的this是当前循环的dom
                //根据参数来设置 dom的样式
                $this.css({
                    backgroundColor: opts.background,
                    color: opts.foreground
                });
            });

        }
    });    //默认参数
    var defaluts = {
        foreground: &#39;red&#39;,
        background: &#39;yellow&#39;
    };
})(window.jQuery);
Copy after login


到这一步,高亮插件基本功能已经具备了。调用代码如下:


$(function () {
    $("p").highLight(); //调用自定义 高亮插件});
Copy after login


这里只能 直接调用,不能链式调用。我们知道jQuey是可以链式调用的,就是可以在一个jQuery对象上调用多个方法,如:
$('#id').css({marginTop:'100px'}).addAttr("title","测试“);
但是我们上面的插件,就不能这样链式调用了。比如:$("p").highLight().css({marginTop:'100px'}); //将会报找不到css方法,原因在与我的自定义插件在完成功能后,没有将 jQuery对象给返回出来。接下来,return jQuery对象,让我们的插件也支持链式调用。(其实很简单,就是执行完我们插件代码的时候将jQuery对像return 出来,和上面的代码没啥区别)


 1 //闭包限定命名空间 2 (function ($) { 3     $.fn.extend({ 4         "highLight": function (options) { 5             var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆盖插件默认参数 6             return this.each(function () {  //这里的this 就是 jQuery对象。这里return 为了支持链式调用 7                 //遍历所有的要高亮的dom,当调用 highLight()插件的是一个集合的时候。 8                 var $this = $(this); //获取当前dom 的 jQuery对象,这里的this是当前循环的dom 9                 //根据参数来设置 dom的样式10                 $this.css({11                     backgroundColor: opts.background,12                     color: opts.foreground13                 });14             });15 16         }17     });18     //默认参数19     var defaluts = {20         foreground: &#39;red&#39;,21         background: &#39;yellow&#39;22     };23 })(window.jQuery);
Copy after login


View Code

4.暴露公共方法 给别人来扩展你的插件(如果有需求的话)
比如的高亮插件有一个format方法来格式话高亮文本,则我们可将它写成公共的,暴露给插件使用者,不同的使用着根据自己的需求来重写该format方法,从而是高亮文本可以呈现不同的格式。


    //公共的格式化 方法. 默认是加粗,用户可以通过覆盖该方法达到不同的格式化效果。
    $.fn.highLight.format = function (str) {        return "<strong>" + str + "</strong>"; 
    }
Copy after login

5.插件私有方法
有些时候,我们的插件需要一些私有方法,不能被外界访问。例如 我们插件里面需要有个方法 来检测用户调用插件时传入的参数是否符合规范。
6.其他的一些设置,如:为你的插件加入元数据插件的支持将使其变得更强大。

完整的高亮插件代码如下:


//闭包限定命名空间(function ($) {
    $.fn.extend({
        "highLight": function (options) {            //检测用户传进来的参数是否合法
            if (!isValid(options))                return this;            var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆盖插件默认参数
            return this.each(function () {  //这里的this 就是 jQuery对象。这里return 为了支持链式调用
                //遍历所有的要高亮的dom,当调用 highLight()插件的是一个集合的时候。
                var $this = $(this); //获取当前dom 的 jQuery对象,这里的this是当前循环的dom
                //根据参数来设置 dom的样式
                $this.css({
                    backgroundColor: opts.background,
                    color: opts.foreground
                });                //格式化高亮文本
                var markup = $this.html();
                markup = $.fn.highLight.format(markup);
                $this.html(markup);
            });

        }
    });    //默认参数
    var defaluts = {
        foreground: &#39;red&#39;,
        background: &#39;yellow&#39;
    };    //公共的格式化 方法. 默认是加粗,用户可以通过覆盖该方法达到不同的格式化效果。
    $.fn.highLight.format = function (str) {        return "<strong>" + str + "</strong>";
    }    //私有方法,检测参数是否合法
    function isValid(options) {        return !options || (options && typeof options === "object") ? true : false;
    }
})(window.jQuery);
Copy after login

调用

        //调用
        //调用者覆盖 插件暴露的共公方法
        $.fn.highLight.format = function (txt) {            return "<em>" + txt + "</em>"
        }
        $(function () {
            $("p").highLight({ foreground: &#39;orange&#39;, background: &#39;#ccc&#39; }); //调用自定义 高亮插件
        });
Copy after login

本文讲解了jQuery插件开发标准写法 ,更多相关内容请关注php中文网。

相关推荐:
JQuery中DOM操作——wrap

React this绑定的几点思考

django 使用 request 获取浏览器发送的参数


The above is the detailed content of Standard writing method for jQuery plug-in development. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template