Jquery plugin compilation learning Summary

Source: Internet
Author: User

Jquery plugin compilation learning Summary

The purpose of writing a plug-in is to encapsulate a series of existing methods or functions so that they can be used repeatedly in other places to facilitate later maintenance and improve development efficiency.

I. Types of plug-ins
JQuery plug-ins are mainly divided into three types.
1. Plug-ins that encapsulate object Methods
2. Plug-ins that encapsulate global functions
3. selector plug-in
Here we mainly discuss the development process of the first plug-in.
Plug-ins that encapsulate object methods:
This plug-in encapsulates object methods and is used to operate jQuery objects obtained by selector. It is the most common plug-in. more than 95% of plug-ins are plug-ins of this type.

II. Key Points of plug-ins
1. All object methods should be appended to jQuery. fn, and all global functions should be appended to the jQuery object itself.
2. Inside the plug-in, this points to the jQuery object currently obtained through the selector, rather than the DOM element.
3. All methods or function plug-ins should end with a semicolon. To be more secure, you can even add a semicolon to the plug-in header to avoid the impact of their nonstandard code on the plug-in.
4. The plug-in should return a jQuery object to ensure chained operation.
5. Use of closures.

3. Closure in Plug-ins
Closure: in simple terms, when an internal function is called outside of its external functions, it forms a closure.
Using the closure feature, you can avoid the impact of internal temporary variables on the global space, and continue to use $ as the alias of jQuery within the plug-in. Common jQuery plug-ins are in the following format:

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

Let's take a look at this Code:

; (Function ($) {// defines a local variable foo, which can be accessed only within the function, and var foo cannot be accessed externally; var bar = function (){//...} // The following sentence adds a global function BAR on the jQuery object. You can use $. BAR () to access the internally defined function bar (), and the internal function bar () can also access foo $. BAR = bar;}) (jQuery );

In fact, this is very similar to the previous blog article about Modular programming, which uses the closure cover concept. However, in Modular programming, the closure can be used to expand the module method, here is the method on the $ object, that is, the jQuery global function plug-in.

Iv. jQuery. extend () method
JQuery provides two methods for extending jQuery functions, namely jQuery. fn. extend and jQuery. extend. The former is used to expand the first of the three types of plug-ins mentioned earlier, and the latter is used to expand the latter two plug-ins. The jQuery. extend () method can be used to expand jQuery objects. It also has a powerful function to extend existing Object objects.

jQuery.extend(target,obj1,obj2,...objn);

Use one or more objects to expand an object, and then return the extended object.
Example:

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

Result:

newOptions = { validate: true,limit: 5,name: "bar" };

Obviously, the features of this method can easily overwrite the default value with input parameters, which is often used in the compilation of plug-ins.

5. Compile the jQuery plug-in
In view of the fact that various forms are frequently encountered during my internship (the online e-commerce platform), in order to avoid repeated work, I learned to write a plug-in that has the simple function of changing the color of a table and clicking on the selected color.
Otherwise, you need to repeat the following code:

$("tbody>tr:odd").addClass("odd");$("tbody>tr:even").addClass("even");$("tbody>tr:has(:checked)").addClass("selected");$("tbody>tr").click(function () {    var hasSelected = $(this).hasClass("selected");    $(this)[hasSelected?"removeClass":"addClass"]  ("selected").find(':checkbox').prop('checked',!hasSelected);});

It does not provide much functionality, but it also understands the specific development process of the plug-in.
First, create a new file jquery. tableBgColor. js, name the plug-in method tableBgColor, and set up the framework:

; (Function ($) {$. fn. extend ({"tableBgColor": function (options) {// set the default value options =$. extend ({odd: "odd", even: "even", selected: "selected"}, options );//... the plug-in code return this; // returns the jQuery object to ensure chained operation}) }}) ;}( jQuery );

Now, we should use the selector to select a table. After the tableBgColor () method is executed, the tr elements in the corresponding table are discolored in each row, when you click a row, the color changes and the corresponding row's checkbox is selected.
Therefore, you only need to slightly modify the code that will be repeated before into the framework:

; (Function ($) {$. fn. extend ({"tableBgColor": function (options) {// The each () method traverses the matching element, because more than one return this element may be matched. each (function () {// set the Default Value options = $. extend ({odd: "odd", even: "even", selected: "selected"}, options); $ ("tbody> tr: odd", this ). addClass (options. odd); $ ("tbody> tr: even", this ). addClass (options. even); $ ("tbody> tr: has (: checked)", this ). addClass ("selected"); $ ("tbody> tr", this ). click (function () {va R hasSelected = $ (this). hasClass (options. selected); $ (this) [hasSelected? "RemoveClass": "addClass"] (options. selected). find (': checkbox'). prop ('checked ',! HasSelected); // note that prop is used instead of attr}); return this ;}}) ;}( jQuery );

Now, the plug-in is complete. Now we can test this plug-in. Construct a table with the id test_table:

 
//... This is omitted

Set the corresponding CSS class:

        table{            text-align: left;            border-spacing: 0;            border-collapse: collapse;        }        td,th{            border: 1px solid #e2e2e2;            padding: 3px;        }        th{            background-color: #1B6540;            color: #fff;        }        .odd{            background-color: #4FA46B;        }        .even{            background-color: #8ECE9F;        }        .selected{            background-color: #ecb6c4;        }

Introduce the plug-in file:

<script src="jquery.min.js"></script><script src="jquery.tableBgColor.js"></script>

Method of calling the plug-in:

    $(function () {        $("#test_table").tableBgColor();    })

The following results are obtained:

Click a row:

Check the connectivity test function: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxwcmUgY2xhc3M9 "brush: java;"> $("#test_table").tableBgColor().find("th").css("background-color","red");

The header turns red:

Success! Perfect!
Now you may feel a little flawed. The plug-in does not write any code to solve the conflict problem. It is not difficult to solve this problem. You just need to change the previous Code as follows:

; (Function ($) {var old = $. fn. tableBgColor; // Save the method to be overwritten in old. // note that the method to define the plug-in is changed so that the following $. fn. tableBgColor. noConflict can call the tableBgColor method normally $. fn. tableBgColor = function (options) {return this. each (function () {// set the Default Value options = $. extend ({odd: "odd", even: "even", selected: "selected"}, options); $ ("tbody> tr: odd", this ). addClass (options. odd); $ ("tbody> tr: even", this ). addClass (options. even); $ ("tbody> tr: has (: Checked) ", this ). addClass ("selected"); $ ("tbody> tr", this ). click (function () {var hasSelected = $ (this ). hasClass (options. selected); $ (this) [hasSelected? "RemoveClass": "addClass"] (options. selected). find (': checkbox'). prop ('checked ',! HasSelected) ;}); return this ;}// defines the noConflict method of the tableBgColor object. After this method is executed, the tableBgColor method is restored to the method reserved in the old one $. fn. tableBgColor. noConflict = function () {$. fn. tableBgColor = old; return this ;}) (jQuery );

You may also feel a little flawed. This table cannot be fully selected. Of course, you can also write a plug-in with the full selection function on your own, however, it should be noted that the full selection function may involve many elements. When designing the html structure, it is best to compile the plug-in function with the plug-in function.

Related Article

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.