JQuery plugin development-jquery-js tutorial

Source: Internet
Author: User
The development of jQuery plug-in fully parses jQuery plug-in includes two types: one is class-level plug-in development, that is, adding a new global function to jQuery is equivalent to adding a method to the jQuery class itself. JQuery's global functions belong to the jQuery namespace, and the other is object-level plug-in development, that is, adding methods to jQuery objects. The following describes the development of the two functions in detail.
1. Class-level plug-in development
The most direct understanding of class-level plug-in development is to add class methods to the jQuery class, which can be understood as adding static methods. A typical example is the $. AJAX () function, which is defined in the namespace of jQuery. The following extensions can be used for class-level plug-in development:
1.1 Add a new global function
To add a global function, we only need to define it as follows:
Java code

The Code is as follows:


JQuery. foo = function (){
Alert ('this is a test. This is only a test .');
};


1.2 add multiple global functions
Add multiple global functions, which can be defined as follows:
Java code

The Code is as follows:


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


The call time is the same as that of a function: jQuery. foo (); jQuery. bar (); or $. foo (); $. bar ('bar ');
1.3 Use jQuery. extend (object );
Java code

The Code is as follows:


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


1.4 Use a namespace
Although a large number of javaScript function names and variable names are not allowed in the jQuery namespace. But it is still inevitable that some functions or variables will conflict with other jQuery plug-ins, so we are used to encapsulating some methods into another custom namespace.
Java code

The Code is as follows:


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


9. The namespace function is still a global function. The method used for calling is as follows:
10. $. myPlugin. foo ();
11. $. myPlugin. bar ('baz ');
With this technique (using an independent plug-in name), we can avoid conflicts between functions in the namespace.
2. Object-level plug-in development
Object-level plug-in development requires the following two forms :,
Form 1:
Java code

The Code is as follows:


1. (function ($ ){
2. $. fn. extend ({
3. pluginName: function (opt, callback ){
4. // Our plugin implementation code goes here.
5 .}
6 .})
7.}) (jQuery );


Form 2:
Java code

The Code is as follows:


1. (function ($ ){
2. $. fn. pluginName = function (){
3. // Our plugin implementation code goes here.
4 .};
5.}) (jQuery );


The above defines a jQuery function with the form parameter $. After the function definition is complete, pass the jQuery real parameter in. Call and execute now. The advantage is that when writing the jQuery plug-in, we can also use the $ alias instead of causing conflicts with prototype.
2.1 declare a name in the JQuery namespace
This is a single plug-in script. If your script contains multiple plug-ins or plug-ins that are mutually inverse (for example, $. fn. doSomething () and $. fn. undoSomething (), you need to declare multiple function names. However, when writing a plug-in, we usually try to use only one name to include all its content. Our example plug-in is named "highlight"
Java code

The Code is as follows:


1. $. fn. hilight = function (){
2. // Our plugin implementation code goes here.
3 .};
4. Our plug-in is called as follows:
5. $ ('# myDiv'). hilight ();


But what if we need to break down our implementation code into multiple functions? There are many reasons: design needs; easier or easier to read implementation; and more in line with object-oriented. This is really a headache. It breaks down the function implementation into multiple functions without adding additional namespaces. To realize that and use functions are the most basic class objects in javascript, we can do this. Like other objects, functions can be specified as attributes. Therefore, we have declared "hilight" as a jQuery attribute object. Any other attribute or function that we need to expose can be declared in the "hilight" function. Continue later.
2.2 accept the options parameter to control the actions of the plug-in
Let's add features for our plug-in to specify the foreground color and background color. We may make options pass to the plug-in function like an options object. For example:
Java code

The Code is 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. // Our plugin implementation code goes here.
10 .};
11. Our plug-in can be called as follows:
12. $ ('# myDiv'). hilight ({
13. foreground: 'blue'
14 .});


2.3 default settings of the exposure plug-in
One improvement of the above Code is to expose the default settings of the plug-in. This makes it easier for plug-in users to overwrite and modify plug-ins with less code. Next we start to use function objects.
Java code

The Code is as follows:


1. // plugin definition
2. $. fn. hilight = function (options ){
3. // Extend our default options with those provided.
4. // Note that the first arg to extend is an empty object-
5. // this is to keep from overriding our "defaults" object.
6. var opts = $. extend ({}, $. fn. hilight. defaults, options );
7. // Our plugin implementation code goes here.
8 .};
9. // plugin defaults-added as a property on our plugin function
10. $. fn. hilight. defaults = {
11. foreground: 'red ',
12. background: 'yellow'
13 .};
14. Now users can include a line like this in their scripts:
15. // This only needs to be called once, and it does not have to be called in the ready Block
16. $. fn. hilight. defaults. foreground = 'blue ';
17. Next we can use the plug-in method like this to set the blue foreground color:
18. $ ('# myDiv'). hilight ();


Now users can include a line like this in their scripts:

The Code is as follows:


// This only needs to be called once and does not have to be 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 users to write a line of code in the default foreground of the plug-in. You can also overwrite these new default values as needed:
// Overwrite the Default background color of the plug-in
$. Fn. hilight. defaults. foreground = 'blue ';
//...
// Call the plug-in using a new default setting
$ ('. HilightDiv'). hilight ();
//...
// Pass the configuration parameters to the plug-in method to overwrite the default settings
$ ('# Green'). hilight ({
Foreground: 'green'
});


2.4 properly expose some functions
This section will expand your plug-ins step by step through interesting methods for the previous Code Section (while allowing others to expand your plug-ins ). For example, we can define a function named "format" in the implementation of the plug-in to format the highlighted text. Our plug-in now looks like this. The implementation of the default format method is under the hiligth function.
Java code

The Code is 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 = export this.html ();
8. // call our format function
9. markup = $. fn. hilight. format (markup );
10. Export this.html (markup );
11 .});
12 .};
13. // define our format function
14. $. fn. hilight. format = function (txt ){
15. return''+ Txt +'';
16 .};


We can easily support other attributes in the options object by allowing a callback function to overwrite the default settings. This is another great way to modify your plug-in. The trick shown here is to further effectively expose the format function so that it can be redefined. With this technique, others can pass their own settings to overwrite your plug-ins. In other words, others can also write plug-ins for your plug-ins.
Considering the useless plug-ins we have created in this article, you may want to know when these will be useful. A real example is the Cycle plug-in. This Cycle plug-in is a slide display plug-in that supports many internal transformations, such as scrolling, sliding, and fading. But in fact, there is no way to define the effects that may apply to each type of Slide change. That is where this scalability is useful. The Cycle plug-in exposes the "transitions" object to users so that they can add their own transformation definitions. The plugin is defined as follows:

The Code is as follows:


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


This technique allows others to define and pass transformation settings to the Cycle plug-in.
2.5 keep private functions
This technique exposes some of your plug-ins to be overwritten. But you need to think carefully about what is exposed in your implementation. Once exposed, you need to maintain any changes to the parameters or semantics in your mind may undermine backward compatibility. A general principle is that if you are not sure whether to expose a specific function, you may not need to do that.
So how can we define more functions without disrupting namespaces or exposing implementations? This is the function of the closure. For demonstration, we will add another "debug" function to our plug-in. This debug function will output the selected element format to the firebug console. To create a closure, we define the entire plug-in as a function.
Java code

The Code is 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)
10. window. console. log ('hilight selection count: '+ $ obj. size ());
11 .};
12 .//...
13.}) (jQuery );


Our "debug" method cannot enter from external closures, so our implementation is private.
2.6 support for Metadata plug-ins
Based on the plug-in you are writing, adding support for the Metadata plug-in can make it more powerful. Personally, I like this Metadata plug-in because it allows you to overwrite the plug-in options with a few "markup" plug-ins (this is useful when creating an example ). It is also very simple to support. Update: There are some optimization suggestions in the comments.
Java code

The Code is 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 change lines do something: it is to test whether the Metadata plug-in is installed. If it is installed, it can expand our options object by extracting the metadata line and adding it to JQuery as the last parameter. extend, it will overwrite any other option settings. Now we can drive behavior from "markup". If we select "markup ":
You can write jQuery. foo (); or $. foo ();
Java code

The Code is as follows:


1.
2.


3. Have a nice day!
4.


5.


6. Have a nice day!
7.


8.


9. Have a nice day!
10.



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

2.7 Integration
The code after the example is completed is as follows:
Java code

The Code is as follows:


1. // create a closure
2. (function ($ ){
3. // plug-in 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 (){
10. $ this = $ (this );
11. // build element specific options
12. var o = $. meta? $. Extend ({}, opts, $ this. data (): opts;
13. // update element styles
14. Define this.css ({
15. backgroundColor: o. background,
16. color: o. foreground
17 .});
18. var markup = export this.html ();
19. // call our format function
20. markup = $. fn. hilight. format (markup );
21. Export this.html (markup );
22 .});
23 .};
24. // Private function: debugging
25. function debug ($ obj ){
26. if (window. console & window. console. log)
27. window. console. log ('hilight selection count: '+ $ obj. size ());
28 .};
29. // define the exposure format Function
30. $. fn. hilight. format = function (txt ){
31. return''+ Txt +'';
32 .};
33. // defaults of the plug-in
34. $. fn. hilight. defaults = {
35. foreground: 'red ',
36. background: 'yellow'
37 .};
38. // closure ends
39.}) (jQuery );


This design allows me to create a powerful compliant plug-in. I hope it can also be done for you.
3. Summary
JQuery provides two methods for development plug-ins:
JQuery. fn. extend (object); add a method to the jQuery object.
JQuery. extend (object); adds a new method to the class to extend the jQuery class itself.
3.1 jQuery. fn. extend (object );
What is fn. It is not difficult to see jQuery code.
JQuery. fn = jQuery. prototype = {
Init: function (selector, context ){//....
//......
};
It turns out that jQuery. fn = jQuery. prototype. It is certainly no stranger to prototype. Although javascript does not have a clear concept of a class, it is more convenient to use a class to understand it. JQuery is a well-encapsulated class. For example, we use the statement $ ("# btn1") to generate a jQuery class instance.
JQuery. fn. extend (object); the extension to jQuery. prototype is to add "member functions" to the jQuery class ". JQuery class instances can use this "member function ".
For example, we want to develop a plug-in and create a Special edit box. When it is clicked, the content in the current edit box of alert is displayed. You can do this:

The Code is as follows:


$. Fn. extend ({
AlertWhileClick: function (){
$ (This). click (function (){
Alert ($ (this). val ());
});
}
});
$ ("# Input1"). alertWhileClick (); // The page is:


$ ("# Input1") is a jQuery instance. When it calls the member method alertWhileClick, the extension is implemented. When it is clicked, the content in the current edit is displayed.
3.2 jQuery. extend (object );
Add a class method to the jQuery class, which can be understood as adding a static method. For example:

The Code is as follows:


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


Add a "static method" for jQuery as add, and then you can use this method at 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.