Detailed description of jQuery plug-in compilation steps and jquery plug-in details

Source: Internet
Author: User

Detailed description of jQuery plug-in compilation steps and jquery plug-in details

This document describes how to write the jQuery plug-in. We will share this with you for your reference. The details are as follows:

Currently, jquery is almost indispensable for web development. Even in version 2010, vs launched Jquery and ui built-in web projects. As for the advantages of using jquery, I will not repeat it here. I know it once I used it. Today we will discuss jquery's plug-in mechanism. jquery has thousands of third-party plug-ins. Sometimes we have written an independent function and want to combine it with jquery, you can use jquery for chained calls. This requires extension of jquery, which is written as a plug-in form. The following is a demo for simple extension of Jquery objects:

// Sample: The jquery object extension method. bold () is used to bold the font. (Function ($) {$. fn. extend ({"bold": function () {// <summary> // bold font // </summary> return this.css ({fontWeight: "bold"}) ;}}) ;}( jQuery );

Call method:

This is a very simple extension. Next we will parse the above Code step by step.

I. jquery plug-in mechanism

To facilitate the creation of plug-ins, jquery provides jQuery. extend () and jQuery. fn. extend () methods.

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

JQuery. extend (object), a parameter used to extend the jQuery class itself, that is, to add a new function to the jQuery class/namespace, or call a static method, for example, jQuery's built-in ajax method uses jQuery. ajax () is called like "class name. method Name "static method call method. The following is an example of jQuery. extend (object:

// Extension of jQuery object itself jQuery. extend ({"minValue": function (a, B) {// <summary> // compare two values, returns the minimum value /// </summary> return a <B? A: B ;}, "maxValue": function (a, B) {/// <summary> // compares two values, returns the maximum value /// </summary> return a> B? A: B ;}}); // call var I = 100; j = 101; var min_v = $. minValue (I, j); // min_v equals 100var max_v =$. maxValue (I, j); // max_v equals 101

Overloaded version:

JQuery. extend ([deep], target, object1, [objectN])

Use one or more other objects to expand an object and return the extended object.
If no target is specified, the jQuery namespace itself is extended. This helps the plug-in author Add a new method for jQuery.
If the first parameter is set to true, jQuery returns a deep copy to recursively copy any objects found. Otherwise, the copy will share the structure with the original object.
Undefined attributes will not be copied, but attributes inherited from the object's prototype will be copied.

Parameters:

Deep: Optional. If it is set to true, recursive merge is performed.
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);

Result:

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

Example 2:

Merge ults and options without modifying defaults.

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

Result:

settings == { validate: true, limit: 5, name: "bar" }empty == { validate: true, limit: 5, name: "bar" }

This overload method is generally used to overwrite the default parameters of the plug-in with custom plug-in parameters when writing the plug-in.

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

First, let's look at what fn is. It is not difficult to see jQuery code.

jQuery.fn = jQuery.prototype = {  init: function( selector, context ) {.....};};

The original jQuery. fn = jQuery. prototype, that is, the prototype of the jQuery object. The jQuery. fn. extend () method is the prototype method for extending the jQuery object. We know that the method on the extension prototype is equivalent to adding a "member method" to the object. The "member method" of the class can only be called by the class object. Therefore, jQuery is used. fn. extend (object) extension method. This "member function" can be used for jQuery class instances ". JQuery. fn. extend (object) and jQuery. extend (object) methods must be distinguished.

Ii. Self-executed anonymous functions/closures

1. What are self-executed anonymous functions?

It refers to a function like this:

(function {// code})();

2. Why (function {// code}) (); can be executed, but function {// code} (); returns an error?

3. Analysis

(1) first, we need to know the differences between the two:

(Function {// code}) is an expression, and function {// code} is a function declaration.

(2). Second, features of js "pre-compilation:

In the "pre-compilation" phase, js will explain the function declaration, but will ignore the table type.

(3 ). when js executes function () {// code} ();, because function () {// code} has been explained in the "pre-compiled" stage, js will skip function () {// code} and attempt to execute ();, so an error will be reported;
When js executes (function {// code}) ();, because (function {// code}) is an expression, js will solve it to get the return value, because the return value is a function, when (); is encountered, it will be executed.
In addition, the method for converting a function to an expression does not have to rely on the grouping operator (). We can also use the void operator ,~ Operator ,! Operator ......

For example:

Plug-in writing in the bootstrap framework:

!function($){//do something;}(jQuery);

And

(function($){//do something;})(jQuery);

It is one thing.

The biggest use of anonymous functions is to create closures (one of the features of the JavaScript language) and build namespaces to reduce the use of global variables.

For example:

Var a = 1; (function () {var a = 100;}) (); alert (a); // pop up 1

3. One-Step JQuery plug-in Encapsulation

Next, let's write a highlighted jqury plug-in.

1. Define a closure area to prevent "contamination" of the plug-in"

// The closure limits the namespace (function ($) {}) (window. jQuery );

2. jQuery. fn. extend (object) Extension jquery method, making plug-ins

// The closure limits the namespace (function ($) {$. fn. extend ({"highLight": function (options) {// do something});}) (window. jQuery );

3. provide default parameters for the plug-in to implement the plug-in Function

// The closure limits the namespace (function ($) {$. fn. extend ({"highLight": function (options) {var opts = $. extend ({}, defaluts, options); // use jQuery. extend overwrites the default extension parameter this. each (function () {// here this is the jQuery object // traverses all the dom to be highlighted. When the highLight () Plug-in is called, it is a set. Var $ this = $ (this); // get the jQuery object of the current dom. here this is the dom of the current loop. // set the dom style using parameters such as javasthis.css ({backgroundColor: opts. background, color: opts. foreground}) ;}}}); // default parameter var defaluts ={ foreground: 'red', background: 'yellow' };}) (window. jQuery );

In this step, the basic functions of the highlighted plug-in are ready. The call code is as follows:

$ (Function () {$ ("p"). highLight (); // call the custom highLight plug-in });

It can only be called directly, not chained. We know that jQuey can be called in a chain, that is, multiple methods can be called on a jQuery object, such:

Detail ('{id'}.css ({marginTop: '100px '}). addAttr ("title", "test ");

However, the plug-in above cannot be called in this chain. For example:

$("p").highLight().css({marginTop:'100px'});

The css method cannot be found because the jQuery object is not returned after the function is completed with the custom plug-in. Next, return jQuery object, so that our plug-in also supports chain call. (In fact, it is very simple, that is, when we execute the plug-in code, we will return jQuery to the image, there is no difference with the above Code)

// The closure limits the namespace (function ($) {$. fn. extend ({"highLight": function (options) {var opts = $. extend ({}, defaluts, options); // use jQuery. extend overwrites the default parameter return this of the plug-in. each (function () {// here this is the jQuery object. Here, return is used to support chained call // to traverse all the dom to be highlighted. When the highLight () Plug-in is called, it is a set. Var $ this = $ (this); // get the jQuery object of the current dom. here this is the dom of the current loop. // set the dom style using parameters such as javasthis.css ({backgroundColor: opts. background, color: opts. foreground}) ;}}}); // default parameter var defaluts ={ foreground: 'red', background: 'yellow' };}) (window. jQuery );

4. Expose public methods to others to expand your plug-in (if necessary)

For example, the highlighted plug-in has a format method to format the highlighted text, so we can write it as public and expose it to the plug-in user, different uses rewrite the format method according to their own needs, but highlight text can render different formats.

// Common formatting method. The default format is bold. You can overwrite this method to achieve different formatting effects. $. Fn. highLight. format = function (str) {return "<strong>" + str + "</strong> ";}

5. Private method of plug-ins

Sometimes, our plug-in requires some private methods and cannot be accessed by the outside world. For example, we need a method in the plug-in to check whether the parameters passed in when the user calls the plug-in comply with the specifications.

6. other settings, such as adding metadata plug-ins to your plug-in will make it more powerful.

The complete highlighted plug-in code is as follows:

// The closure limits the namespace (function ($) {$. fn. extend ({"highLight": function (options) {// checks whether user-passed parameters are valid if (! IsValid (options) return this; var opts = $. extend ({}, defaluts, options); // use jQuery. extend overwrites the default parameter return this of the plug-in. each (function () {// here this is the jQuery object. Here, return is used to support chained call // to traverse all the dom to be highlighted. When the highLight () Plug-in is called, it is a set. Var $ this = $ (this); // get the jQuery object of the current dom. here this is the dom of the current loop. // set the dom style using parameters such as javasthis.css ({backgroundColor: opts. background, color: opts. foreground}); // format the highlighted text var markup = export this.html (); markup = $. fn. highLight. format (markup); export this.html (markup) ;}}); // default parameter var defaluts ={ foreground: 'red', background: 'yellow '}; // common formatting method. the default format is bold. You can overwrite this method to achieve different formatting effects. $. Fn. highLight. format = function (str) {return "<strong>" + str + "</strong>" ;}// private method to check whether the parameter is valid function isValid (options) {return! Options | (options & typeof options = "object ")? True: false ;}}) (window. jQuery );

Call:

// Call // the method that the caller overwrites the common public method exposed by the plug-in $. fn. highLight. format = function (txt) {return "<em>" + txt + "</em>" }$ (function () {$ ("p "). highLight ({foreground: 'Orange ', background:' # ccc '}); // call the custom highLight plug-in });

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.