jquery Plugin Authoring

Source: Internet
Author: User

The purpose of writing a plug-in: to give an existing series of methods or functions in a package for reuse in other places, convenient for later maintenance and improve development efficiency.

jquery plug-in type

There are 3 main types of jquery plugins:
1. Plug-in for encapsulating object methods (object-level component development)
This plug-in is the most common plug-in that encapsulates object methods and is used to manipulate jquery objects obtained through selectors. Such plugins can play a powerful role in the jquery selector.
The method that hangs under the jquery prototype , so that the jquery object instance obtained by the selector can also share the method, also known as the dynamic method ( instance method )

function(){    //do something}//这里$.fn===$.prototype//例如:addClass()、attr()等,需要创建实例来调用

2. Plug-in for encapsulating global functions (class-level component development)
You can add separate functions to the jquery namespace, such as the Jquery.noconflict () method, which is a plugin attached to the kernel as a global function within jquery.
Add a new global function to the jquery namespace, also known as a static method

function(){    //do something}//例如:$.Ajax()、$.extend()

3. Selector plug-in
In some cases, a selector plug-in is required.

Basic points of the plugin
    • The file name of the jquery plugin is named jquery. [plugin name].js to avoid confusion with other JavaScript library plugins.]
    • All object methods should be attached to the Jquery.fn object, and all global functions should be attached to the jquery object itself
    • Inside the plug-in, this refers to the jquery object currently acquired through the selector.
    • All elements can be traversed by This.each.
    • All methods or function plug-ins should end with a semicolon, or the problem may occur when compressing. To be more secure, you can even add a semicolon to the plugin's head to prevent other people's nonstandard code from affecting the plugin.
    • The plugin should return a jquery object to ensure that the plug-in can be chained.
Common plug-in forms
//note for better compatibility, there is a semicolon before starting  ;(function   ($)  {    //here as the formal parameter of the anonymous function     //Place the code here, you can use $ as an abbreviated alias for jquery     //defines a local variable foo, which can only be accessed inside the function and cannot be accessed externally     var  foo; var  bar = function   ()  { //functions inside anonymous functions can access Foo, Even when you call bar () outside of an anonymous function, you can access Foo inside the bar (). But directly accessing Foo outside of the anonymous function is not a } $.    bar = bar; //this statement lets the function bar () inside the anonymous function escape to the globally accessible scope so that it can be called outside the anonymous function, Jquery.bar () to access the internally defined function bar (), and the internal function bar () can also access the variable foo } in the anonymous function (jQuery); //here to pass jquery as an argument to the anonymous function   
closures in plugins

With regard to closures, ECMAScript defines them by allowing the use of intrinsic functions (that is, function definitions and function expressions in the function body of another function), and that these intrinsics can access all the local variables, arguments, and other intrinsics declared in the outer function in which they reside. When one of these intrinsics is called outside the outer function that contains them, a closure is formed. That is, the intrinsic function is executed after the external function returns. When this inner function executes, it makes it necessary to access the local variables, arguments, and other intrinsic functions of its external function. The values of these local variables, parameters, and function declarations are the values that are returned by the external function, but are also affected by intrinsic functions.

We use closures to access and modify local variables in the included function
By using the characteristics of closures, you can avoid internal temporary variables that affect global space, and you can continue to use $ as a jquery alias within the plug-in.

provides default options for plug-ins

Plugins should have some options that can be set by the developer themselves as needed, so providing a restore default option is necessary. You can set these options by using the Extend feature of jquery:

var defaults = {//Default configuration Parameters' container ' : ' #container ',//Container' sections ' : '. Section ',//Child containers' easing ' : ' ease ',//Special effects mode, ease-inch, Ease-out,linear' Duration ' :  +,//Time of each animation execution' pagination ' : true,//Whether to show paging' Loop ' : false,//Whether to loop' keyboard ' : true,//Whether the keyboard is supported' Direction ' : ' Vertical ',//Sliding direction horizontal,vertical,};opts =$.Extend ({}, defaults, options| | {});

jquery provides two ways to extend the functionality of jquery: Jquery.extend () and JQuery.fn.extend (). Both methods accept a parameter that is of type object. The "name/value pairs" of the object objects represent "function or method name/function Body", respectively.

jquery.extend () usage

The Jquery.extend () method can also be used to extend an existing object object, in addition to extending the jquery object.
To add an object's properties to a jquery object
Demo:

<script type="text/javascript" src="Jquery-2.1.4.js"> </script><script type="Text/javascript">$ (function(){var obj1 = {apple:0, banana:{weight:52,price:cherry: +}; Jquery.extend (OBJ1); //This write is to add the properties of the Obj1 object to the JQuery object console.log (jquery.apple); //0 Console.log (Jquery.banana); //object {weight:52, price:100} Console.log (Jquery.cherry); //97});    </script>

extends an object with one or more other objects, and then returns the extended object.
Demo:

<script type="text/javascript" src="Jquery-2.1.4.js"> </script><script type="Text/javascript">/  * This example merges the Obj1 object and the Obj2 object, modifies and returns the Obj1 object */$ (function(){var obj1 = {Nam    E:"Lisi", Job:"worker", Age: +};    var obj2 = {name:"Wangwu", Age:+, Address:"Dalian" }; $.extend (OBJ1,OBJ2); //Default first parameter is False, that is, a shallow copy of Console.log (OBJ1); //object {name: "Wangwu", Job: "Worker", age:100, Address: "Dalian"});    </script>

Shallow copy:

<script type="text/javascript" src="Jquery-2.1.4.js"> </script><script type="Text/javascript">$( function(){    varObj1 = {Apple:0, Banana:{weight: the, Price: -}, Cherry: the};varObj2 = {banana:{price: $}, Durian: -};varobj = $.extend (obj1,obj2);varObj1 = $.extend (false, OBJ1,OBJ2);//Default first parameter is False, shallow copyConsole.log (JSON. stringify (obj));//{"Apple": 0, "banana": {"Price": $, "cherry": $, "Durian":Console.log (JSON. Stringify (OBJ1));//From the output of the results can be seen, banana this key value was replaced});</script>

deep Copy: Nested objects are also recursively merged

<script type="text/javascript" src="Jquery-2.1.4.js"> </script><script type="Text/javascript">$ (function   ()  { var  obj1 = {Apple:0< /span>, Banana:{weight:52 , Price:100 }, Cher    Ry:97 }; var  obj2 = {Banana:{price:200 }, durian:<    Span class= "Hljs-number" >100 }; var  obj = $.extend (true , Obj1,obj2); //the first parameter True indicates a deep copy of  Console.log (json . Stringify (obj)); Span class= "hljs-comment" >//{"Apple": 0, "banana": {"Weight": "Price": $, "cherry": $, "Durian": $  //deep copy is a recursive merge that overrides an existing attribute value and adds a property that does not have a  </script>

Comparison of deep and shallow copy results:

//deep copy { "Apple" : 0 , " banana ": {" weight ": Span class= "Hljs-number" >52 ,  "price" : 200 }, "Cherry" : 97 ,  "durian" : 100 }//Shallow copy//{  "Apple" : 0 ,  "banana" : { "price" : 200 },  "Cherry" : 97 , : 100 }  

The result of the shallow copy directly replaces the value of the banana, and the deep copy changes the value of the banana by merging, rather than simply replacing it directly.
the Jquery.extend () method is often used to set a series of default parameters for a plug-in method
Demo:

<script type="text/javascript" src="Jquery-2.1.4.js"> </script><script type="Text/javascript">$( function(){     function fn(options){Options = $.extend ({name:"Bar", Length:5, DataType:"xml"/ * Default parameter settings * /},options);returnOptions } console.log (fn ({name:"a", Length:6, DataType:"JSON"}));//object {name: "A", Length:6, DataType: "JSON"}Console.log (FN ({name:"B", Length:7}));//object {name: "B", Length:7, DataType: "xml"}Console.log (FN ({name:"C"}));//object {name: "C", Length:5, DataType: "xml"}Console.log (FN ());//object {name: "Bar", Length:5, DataType: "xml"}});</script>

When we call the FN () method, we set the corresponding value in the passed parameter options object, then we use the value of the setting, otherwise we use the default value. By using the $.extend () method, it is convenient to override the default value with the passed-in parameters.

jquery Plugin Authoring Jquery.color plug-in
<! DOCTYPE html><html><head>    <meta charset="Utf-8">    <meta http-equiv="x-ua-compatible" content="Ie=edge" >    <title>Jquery.color Plug-in</title>    <style type="Text/css"> . Red{  color: red; }            </style></head><body><div class="Red">Red</div><div class="Blue" style="Color:blue;" >Blue</div><div class="Yellow" style="Color:yellow;" >Yellow</div><script type="text/javascript" src="Jquery-2.1.4.js" ></script><script type="text/javascript" src="JQuery.color.js"> </script><script type="Text/javascript"> //plug-in application $ (function(){ console.log ("div"). Color ("Red") );});</script></body></html>

JQuery.color.js

;(function($){    $.fn.extend({        "color":function(value){            returnthis.css("color",value);//设置字体颜色值        }    });})(jQuery);/*这里给这个方法提供一个参数value,如果调用方法的时候传递了value这个参数,那么就是用这个值来设置字体颜色,否则就是获取匹配元素的字体颜色的值 */

A few good posts are recommended:
10 tips for creating a better jquery Plugin

jquery Plugin Authoring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.