jquery Plugin Development Full analytic _jquery

Source: Internet
Author: User
Tags closure extend function definition
The development of the jquery plug-in includes two kinds: a class-level plug-in development that adds a new global function to jquery, which is equivalent to adding a method to the jquery class itself. jquery's global functions are functions that belong to the jquery namespace, and the other is object-level plug-in development, which adds methods to the JQuery object. The following is a detailed description of the development of the two functions.
1, class-level plug-in development
The most straightforward understanding of class-level plug-in development is to add a class method to the jquery class, which can be understood as adding a static method. The typical example is $. AJAX () This function defines a function in the namespace of jquery. Plug-in development for class level can be extended in the following ways:
1.1 Add a new global function
To add a global function, we just need to define the following:
Java code
Copy Code code as follows:

Jquery.foo = function () {
Alert (' This is a test. This is a test. ');
};

1.2 Adding multiple global functions
To add more than one global function, you can use the following definition:
Java code
Copy Code code as follows:

Jquery.foo = function () {
Alert (' This is a test. This is a test. ');
};
Jquery.bar = function (param) {
Alert (' This function takes a parameter, which is "' + param + '". ');
};

The call is the same as a function: Jquery.foo (); Jquery.bar (); or $.foo (); $.bar (' Bar ');
1.3 Using Jquery.extend (object);
Java code

Copy Code code as follows:

Jquery.extend ({
Foo:function () {
Alert (' This is a test. This is a test. ');
},
Bar:function (param) {
Alert (' This function takes a parameter, which is "' + param + '". ');
}
});

1.4 Using namespaces
Although in the jquery namespace, we prohibit the use of a large number of JavaScript function names and variable names. But it is still inevitable that some functions or variables will be in conflict with other jquery plug-ins, so we are accustomed to encapsulating some methods into another custom namespace.
Java code
Copy Code code as follows:

1.jquery.myplugin = {
2.foo:function () {
3.alert (' This is a test '. This is a test. ');
4.},
5.bar:function (param) {
6.alert (' This function takes a parameter, which is ' ' + param + ' ". ');
7.}
8.};

9. A function that takes a namespace is still a global function, and the method used when invoked:
10.$.myplugin.foo ();
11.$.myplugin.bar (' Baz ');
With this technique (using a standalone plug-in name), we can avoid the conflict of functions within the namespace.
2, Object-level plug-in development
The object-level plug-in development requires two forms, such as:
Form 1:
Java code
Copy Code code as follows:

1. (function ($) {
2.$.fn.extend ({
3.pluginname:function (Opt,callback) {
4.//We plugin implementation code goes here.
5.}
6.})
7.}) (JQuery);

Form 2:
Java code
Copy Code code as follows:

1. (function ($) {
2.$.fn.pluginname = function () {
3.//We plugin implementation code goes here.
4.};
5.}) (JQuery);

This defines a jquery function, the parameter is $, and after the function definition is complete, the jquery argument is passed in. Call execution now. The advantage of this is that when we write the jquery plugin, we can also use the $ alias without causing conflicts with prototype.
2.1 Declaring a name under the jquery namespace
This is a single plugin script. If your script contains multiple plug-ins, or reciprocal plug-ins (for example, $.fn.dosomething () and $.fn.undosomething ()), then you need to declare multiple function names. However, usually when we write a plug-in, we try to use only one name to contain all of its contents. Our sample plug-in is named "Highlight"
Java code
Copy Code code as follows:

1.$.fn.hilight = function () {
2.//We plugin implementation code goes here.
3.};
4. Our plug-ins are called by this way:
5.$ (' #myDiv '). Hilight ();

But what if we need to decompose our implementation code into multiple functions? There are a number of reasons: design needs; This is easier or easier to read, and more in line with object-oriented. It's really a hassle to break down functionality into multiple functions without adding extra namespaces. We can do this by recognizing and leveraging functions as the most basic class object in JavaScript. Like other objects, a function can be specified as a property. So we have declared "Hilight" as a Property object of jquery, any other attribute or function that we need to expose, and can be declared in the "hilight" function. Continue later.
2.2 Accept the options parameter to control the behavior of the plug-in
Let's add functionality for our plugins to specify foreground and background colors. We might let the option pass to the plug-in function like a options object. For example:
Java code
Copy Code code as follows:

1.//Plugin Definition
2.$.fn.hilight = function (options) {
3. var defaults = {
4. Foreground: ' Red ',
5. Background: ' Yellow '
6.};
7.//Extend Our default options with those provided.
8. var opts = $.extend (defaults, options);
9.//We plugin implementation code goes here.
10.};
11. Our plug-ins can be invoked like this:
12.$ (' #myDiv '). Hilight ({
Foreground: ' Blue '
14.});

2.3 Exposing the plugin's default settings
One of the improvements we should have to the code above is to expose the default settings for Plug-ins. This makes it easier for plug-in users to overwrite and modify plug-ins with less code. Next we start using the function object.
Java code
Copy Code code as follows:

1.//Plugin Definition
2.$.fn.hilight = function (options) {
3.//Extend Our default options with those provided.
4.//Note that the ' the ' the ' the ' the ' the ' to extend ' an empty object-
5.//This are to keep from overriding our "Defaults" object.
6. var opts = $.extend ({}, $.fn.hilight.defaults, options);
7.//We plugin implementation code goes here.
8.};
9.//plugin defaults-added as a, our plugin function
10.$.fn.hilight.defaults = {
Foreground: ' Red ',
Background: ' Yellow '
13.};
14. Now the user can include a line like this in their script:
15.//This only needs to be called once and not necessarily in the ready block
16.$.fn.hilight.defaults.foreground = ' Blue ';
17. Next we can use the plug-in method like this, and it sets the blue foreground color:
18.$ (' #myDiv '). Hilight ();

Now the user can include a line like this in their script:
Copy Code code as follows:

This only needs to be called once and is not necessarily called in the Ready block
$.fn.hilight.defaults.foreground = ' Blue ';
Next we can use the plug-in method like this, and it sets the blue foreground color:
$ (' #myDiv '). Hilight ();
As you can see, we allow the user to write a line of code in the plugin's default foreground color. And the user still has the option to overwrite these new defaults when needed:
Overwrite plugin default background color
$.fn.hilight.defaults.foreground = ' Blue ';
// ...
Invoke the plug-in using a new default setting
$ ('. Hilightdiv '). Hilight ();
// ...
Override default settings by passing configuration parameters to the plug-in method
$ (' #green '). Hilight ({
Foreground: ' Green '
});

2.4 Appropriate exposure some functions
This section will step through the previous code to extend your plugin in an interesting way (while allowing others to extend your plugin). For example, the implementation of our plug-in can define a function called "format" to format the highlighted text. Our plugin now looks like this, and the implementation part of the default format method is under the Hiligth function.
Java code
Copy Code code as follows:

1.//Plugin Definition
2.$.fn.hilight = function (options) {
3.//iterate and reformat each matched element
4. Return This.each (function () {
5. var $this = $ (this);
6.//...
7. var markup = $this. HTML ();
8.//Call our Format function
9. Markup = $.fn.hilight.format (markup);
$this. HTML (markup);
11.});
12.};
13.//Define our Format function
14.$.fn.hilight.format = function (TXT) {
15.return ' <strong> ' + txt + ' </strong> ';
16.};

We can easily support other properties in the options object by allowing a callback function to override the default settings. This is another excellent way to modify your plugin. The trick shown here is to further effectively expose the format function so that he can be redefined. With this technique, other people are able to pass their own settings to overwrite your plugin, in other words, so that others can also write plug-ins for your plugin.
Given the useless plug-ins that we built in this article, you might want to know when it might be useful. A real example is the cycle plugin. This cycle plugin is a sliding display plugin that can support many internal transformations to scroll, slide, fade, and so on. In practice, however, there is no way to define the effect that might apply to each type of sliding change. That's where this extensibility is useful. The cycle plug-in exposes "transitions" objects to the consumer, enabling them to add their own transformation definitions. The plug-ins are defined like this:
Copy Code code as follows:

$.fn.cycle.transitions = {
// ...
};

This technique enables others to define and pass transformations to the cycle plug-in.
2.5 Keeping private functions private
This technique exposes you to a part of the plugin that is very powerful to be covered. But you need to think carefully about the exposed parts of your implementation. Once exposed, you need to keep any changes in your mind about parameters or semantics that might break backwards compatibility. One reason is that if you are not sure whether to expose a particular function, then you may not need to do that.
So how do we define more functions without disrupting namespaces and not exposing implementations? This is the function of closures. To demonstrate, we will add another "debug" function to our plugin. The debug function will format the selected element for the output to the Firebug console. In order to create a closure, we will wrap the entire plugin definition in a function.
Java code
Copy Code code as follows:

1. (function ($) {
2.//Plugin definition
3. $.fn.hilight = function (options) {
4. Debug (this);
5.//...
6.};
7.//Private function for debugging
8. Function Debug ($obj) {
9. If (Window.console && window.console.log)
Window.console.log (' Hilight selection count: ' + $obj. Size ());
11.};
12.//...
(JQuery);

Our "Debug" method cannot be entered from an external closure, so it is private for our implementation.
2.6 Support Metadata Plugin
On the basis of the plug-ins you are writing, adding support for the metadata plug-in can make him more powerful. Personally, I like this metadata plugin because it lets you use a few "markup" to overwrite the plugin options (this is useful when creating an example). And it's very simple to support it. Update: There is a little tuning suggestion in the note.
Java code
Copy Code code as follows:

1.$.fn.hilight = function (options) {
2.//...
3.//Build main options before element iteration
4. var opts = $.extend ({}, $.fn.hilight.defaults, options);
5. Return This.each (function () {
6. var $this = $ (this);
7.//Build element specific options
8. var o = $.meta? $.extend ({}, OPTs, $this. Data ()): opts;
9.//...

These changes have done something: it is to test whether the metadata plugin is installed if it is installed, it can expand our options object by extracting the metadata this line as the last parameter added to the Jquery.extend, then it will overwrite any other option settings. Now we can drive behavior from "markup" if we choose "Markup":
The call can be written like this: Jquery.foo (); or $.foo ();
Java code
Copy Code code as follows:

1.<!--Markup-->
2.<div class= "hilight {background: ' Red ', foreground: ' White '} ' >
3. Have a nice day!
4.</div>
5.<div class= "Hilight {foreground: ' Orange '}" >
6. Have a nice day!
7.</div>
8.<div class= "hilight {background: ' green '}" >
9. Have a nice day!
10.</div>

11. Now we can highlight which Div uses only one line of script:
12.$ ('. Hilight '). Hilight ();

2.7 Integration
Here's how to make our example complete after the code:
Java code
Copy Code code as follows:

1.//Create a closed package
2. (function ($) {
3.//Plugin definition
4. $.fn.hilight = function (options) {
5. Debug (this);
6.//Build main options before element iteration
7. var opts = $.extend ({}, $.fn.hilight.defaults, options);
8.//iterate and reformat each matched element
9. Return This.each (function () {
$this = $ (this);
One.//Build element specific options
var o = $.meta? $.extend ({}, OPTs, $this. Data ()): opts;
//Update element styles
$this. CSS ({
Backgroundcolor:o.background,
Color:o.foreground
17.});
var markup = $this. HTML ();
//Call our Format function
Markup = $.fn.hilight.format (markup);
$this. HTML (markup);
22.});
23.};
24.//Private Function: Debugging
function Debug ($obj) {
if (window.console && window.console.log)
Window.console.log (' Hilight selection count: ' + $obj. Size ());
28.};
29.//define Exposure Format function
$.fn.hilight.format = function (TXT) {
Return ' <strong> ' + txt + ' </strong> ';
32.};
33.//Plugin Defaults
$.fn.hilight.defaults = {
Foreground: ' Red ',
Background: ' Yellow '
37.};
38.//Closure End
(JQuery);

This design has allowed me to create powerful plug-ins that conform to specifications. I hope it can make you do it too.
3, Summary
jquery has two methods for developing Plug-ins, respectively:
JQuery.fn.extend (object); Add a method to the jquery object.
Jquery.extend (object); To extend the jquery class itself. Adds a new method to the class.
3.1 JQuery.fn.extend (object);
What is FN? See the jquery code, it's not hard to find.
Jquery.fn = Jquery.prototype = {
Init:function (Selector, context) {//....
//......
};
The original Jquery.fn = Jquery.prototype. It's certainly not strange to prototype. Although JavaScript does not have a well-defined class concept, it is more convenient to use classes to understand it. jquery is a very nicely encapsulated class, for example, we use statement $ ("#btn1") to generate an instance of a jquery class.
JQuery.fn.extend (object); The extension to Jquery.prototype is to add a "member function" to the jquery class. Examples of jquery classes can use this "member function".
For example, we want to develop a plugin, make a special edit box, when it is clicked, alert the contents of the current edit box. Can do this:
Copy Code code as follows:

$.fn.extend ({
Alertwhileclick:function () {
$ (this). Click (function () {
Alert ($ (this). Val ());
});
}
});
$ ("#input1"). Alertwhileclick (); On the page is:

$ ("#input1") is a jquery instance, and when it calls the Member method Alertwhileclick, it expands, which pops up the contents of the current editor each time it is clicked.
3.2 Jquery.extend (object);
Adding a class method to the jquery class can be understood as adding a static method. Such as:
Copy Code code as follows:

1.$.extend ({
2.add:function (a,b) {return a+b;}
3.});

Add a "static method" for jquery, and then you can use this method in the place where jquery is introduced, $.add (3,4); Return 7

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.