Home  >  Article  >  Web Front-end  >  Full analysis of jQuery plug-in development_jquery

Full analysis of jQuery plug-in development_jquery

WBOY
WBOYOriginal
2016-05-16 17:49:25640browse

There are two types of jQuery plug-in development: one is class-level plug-in development, that is, adding new global functions to jQuery, which is equivalent to adding methods to the jQuery class itself. jQuery's global functions are functions that belong to the jQuery namespace. The other is object-level plug-in development, which is to add methods to jQuery objects. The development of the two functions is described in detail below.
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 jQuery namespace. Plug-in development at the class level can be extended in the following forms:
1.1 Add a new global function
To add a global function, we only need to define it as follows:
Java code

Copy 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
To add multiple global functions, you can use the following definition:
Java code
Copy 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 ' ".');
};

is called the same as a function: jQuery.foo();jQuery.bar(); or $.foo();$.bar ('bar');
1.3 Use jQuery.extend(object);
Java code

Copy 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 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 function or variable names will conflict with other jQuery plug-ins, so we are used to encapsulating some methods into another custom namespace.
Java code
Copy 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 .Function using namespace is still a global function, the method used when calling:
10.$.myPlugin.foo();
11.$.myPlugin.bar('baz');
Passed With this trick (using separate plugin names), we can avoid namespace function conflicts.
2. Object-level plug-in development
Object-level plug-in development requires the following two forms:,
Form 1:
Java code
Copy 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
Copy code The code is as follows:

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

A jQuery function is defined above, and the formal parameter is $. After the function definition is completed, pass the jQuery actual parameter in. It will be called and executed immediately. The advantage of this is that when we write a jQuery plug-in, we can also use the $ alias without causing conflict with the 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 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 strive to use only one name to encompass all of its contents. Our example plugin is named "highlight"
Java code
Copy code The code is as follows:

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

But what if we need to decompose our implementation code into multiple functions? There are many reasons: design needs; This is easier or more readable to implement; and it is more object-oriented. This is a real hassle, breaking the functionality into multiple functions without adding unnecessary namespaces. We can do this out of recognition and utilization of functions as the most basic class objects in JavaScript. Just like other objects, functions can be specified as properties. Therefore, we have declared "hilight" as a jQuery property object. Any other properties or functions we need to expose can be declared as properties in the "hilight" function. Continue later.
2.2 Accepting the options parameter to control the behavior of the plugin
Let’s add the ability to specify the foreground and background colors to our plugin. We might pass the options to the plugin function as an options object. For example:
Java code
Copy 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 like this:
12.$('#myDiv').hilight({
13. foreground: 'blue'
14 .});

2.3 Exposing the default settings of the plug-in
One improvement we should make to the above code is to expose the default settings of the plug-in. This makes it easier for users of the plugin to overwrite and modify the plugin with less code. Next we start using function objects.
Java code
Copy 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 does not have to be called in the ready block
16.$.fn.hilight.defaults.foreground = 'blue';
17. Next we can use the plug-in like this method, which sets the foreground color to blue:
18.$('#myDiv').hilight();

Now users can include a line like this in their scripts Here:
Copy code 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 it like this The plugin's method, as a result it sets the blue foreground color:
$('#myDiv').hilight();
As you can see, we allow the user to write a line of code that sets the plugin's default foreground color. And users can still selectively override these new default values ​​when needed:
// Override the default background color of the plug-in
$.fn.hilight.defaults.foreground = 'blue';
// ...
// Call the plugin with a new default setting
$('.hilightDiv').hilight();
// ...
// Pass Configuration parameters to plugin methods to override default settings
$('#green').hilight({
foreground: 'green'
});

2.4 Appropriate Exposing some functions
will step by step extend your plug-in in interesting ways to the previous code (and let others extend your plug-in). For example, our plug-in implementation can define a function called "format" to format highlighted text. Our plug-in now looks like this, the implementation of the default format method is under the hiligth function.
Java code
Copy 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 = $this.html();
8. // call our format function
9. markup = $ .fn.hilight.format(markup);
10. $this.html(markup);
11. });
12.};
13.// define our format function
14.$.fn.hilight.format = function(txt) {
15.return '' txt '';
16.};

We easily support other properties in the options object by allowing a callback function to override the default settings. This is another great way to modify your plugins. The technique shown here is to further effectively expose the format function so that it can be redefined. With this technique, others can override your plugin by passing their own settings, in other words, so that others can write plugins for your plugin.
Considering the useless plugins we created in this article, you may be wondering when exactly these would be useful. A real example is the Cycle plug-in. This Cycle plug-in is a sliding display plug-in, which can support many internal transformation effects to scroll, slide, fade away, etc. But in practice, there is no way to define every type of effect that might be applied to a sliding change. That's where this extensibility is useful. The Cycle plugin exposes "transitions" objects to users, allowing them to add their own transformation definitions. The definition in the plug-in is like this:
Copy the code The code is as follows:

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

This trick enables others to define and pass transformation settings to Cycle plugins.
2.5 Keep private functions private
This technique is very powerful in exposing part of your plugin to be overridden. But you need to think carefully about the exposed parts of your implementation. Once exposed, you need to keep in mind that any changes to parameters or semantics may break backward compatibility. A general rule of thumb is that if you're not sure whether to expose a particular function, then you probably don't need to do that.
So how do we define more functions without messing up the namespace or exposing the implementation? This is the function of closures. To demonstrate, we will add another "debug" function to our plugin. This debug function will output the selected element format to the firebug console. To create a closure, we will wrap the entire plugin definition in a function.
Java code
Copy 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 is not accessible from the outer closure and is therefore private to our implementation.
2.6 Support for Metadata plug-ins
Based on the plug-in you are writing, adding support for Metadata plug-ins can make it more powerful. Personally, I like this Metadata plugin because it lets you use a few "markup" options to override the plugin (which is very useful when creating examples). And supporting it is very simple. Update: A little optimization suggestion in the comments.
Java code
Copy 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 some Thing: It tests whether the Metadata plugin is installed. If it is installed, it can extend our options object by extracting the metadata line and adding it as the last parameter to JQuery.extend, which will now override any other options settings. We can drive behavior from "markup", if we select "markup":
When calling, we can write: jQuery.foo(); or $.foo();
Java code
Copy code The code is as follows:

1.
2 .

3. Have a nice day!
4.

5.< ;div class="hilight { foreground: 'orange' }">
6. Have a nice day!
7.

8.

9. Have a nice day!
10.


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

2.7 Integration
The following code makes our example complete:
Java code
Copy code The code is as follows:

1.// Create a closure
2.(function($) {
3. // Definition of plug-in
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. $this.css({
15. backgroundColor: o.background,
16. color: o.foreground
17. });
18. var markup = $this.html();
19. // call our format function
20. markup = $.fn.hilight.format(markup );
21. $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 exposed format function
30. $.fn.hilight.format = function(txt) {
31. return '' txt ' ';
32. };
33. // Plug-in defaults
34. $.fn.hilight.defaults = {
35. foreground: 'red',
36. background : 'yellow'
37. };
38.// End of closure
39.})(jQuery);

This design has allowed me to create a powerful plug-in that conforms to the specification. I hope it enables you to do the same.
3. Summary
jQuery provides two methods for developing plug-ins, namely:
jQuery.fn.extend(object); Add methods to jQuery objects.
jQuery.extend(object); To extend the jQuery class itself. Add new methods to the class.
3.1 jQuery.fn.extend(object);
What is fn. Looking at the jQuery code, it's not hard to find.
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {//....
//......
};
Original jQuery.fn = jQuery.prototype. You are definitely familiar with prototype. Although JavaScript does not have a clear concept of classes, it is more convenient to use classes to understand it. jQuery is a very well-encapsulated class. For example, if we use the statement $("#btn1"), an instance of the jQuery class will be generated.
jQuery.fn.extend(object); To extend jQuery.prototype is to add "member functions" to the jQuery class. Instances of the jQuery class can use this "member function".
For example, we want to develop a plug-in to create a special edit box. When it is clicked, the content in the current edit box will be alerted. You can do this:
Copy code The code is as follows:

$.fn.extend({
alertWhileClick:function(){
$(this).click(function(){
alert($(this).val());
});
}
});
$("#input1").alertWhileClick(); //On the page:

$("#input1") is a jQuery instance, when it calls a member method After alertWhileClick, the extension is implemented. Every time it is clicked, it will pop up the current editing content first.
3.2 jQuery.extend(object);
Add a class method to the jQuery class, which can be understood as adding a static method. For example:
Copy code The code is as follows:

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

will add a "static method" called add for jQuery, and then you can introduce it For jQuery, use this method, $.add(3,4); //return 7
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:JavaScript Advanced Programming (3rd Edition) Study Notes 8 js Functions (Part 2)_Basic KnowledgeNext article:JavaScript Advanced Programming (3rd Edition) Study Notes 8 js Functions (Part 2)_Basic Knowledge

Related articles

See more