Full Analysis of jQuery plug-in development
There are two types of jQuery plug-in development:
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
The global function belongs to the jQuery namespace function, and the other is object-level plug-in development, that is, adding methods to jQuery objects. Lower
The development of the two functions is described 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. The typical example is
Is the $. AJAX () function, which is defined in the namespace of jQuery. You can use the following methods to develop class-level plug-ins:
Row extension:
1.1 Add a new global function
To add a global function, we only need to define it as follows:
jQuery.foo = function() {alert('This is a test. This is only a test.');};
You can write jQuery. foo (); or $. foo ();
1.2 add multiple global functions
Add multiple global functions, which can be defined 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 );
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 may conflict with other jQuery plug-ins, so we are used to encapsulating some methods into another custom namespace.
jQuery.myPlugin = {foo:function() {alert('This is a test. This is only a test.');},bar:function(param) {alert('This function takes a parameter, which is "' + param + '".');}};
The namespace function is still a global function. The method used for calling is as follows:
$.myPlugin.foo();$.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:
(function($) {$.fn.extend({pluginName: function(opt, callback) {// Our plugin implementation code goes here.}})})(jQuery);
Form 2:
(function($) {$.fn.pluginName = function() {// Our plugin implementation code goes here.};})(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
Use a name to include all its contents. Our example plug-in is named "highlight"
$.fn.hilight = function() {// Our plugin implementation code goes here.};
Our plug-in is called like this:
$('#myDiv').hilight();
But what if we need to break down our implementation code into multiple functions? There are many reasons: design needs; it is easier to do so
Or easier to read; and this is more in line with object-oriented. This is really a headache. It breaks down the function implementation into multiple functions without adding additional functions.
Namespace. To realize that and use functions are the most basic class objects in javascript, we can do this. Just like other objects,
Functions can be specified as attributes. Therefore, we have declared "hilight" as the property object of jQuery. any other property or function we
Attributes that need to be exposed 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 an options object like an options object
Plug-in functions. For example:
// plugin definition$.fn.hilight = function(options) {var defaults = {foreground: 'red',background: 'yellow'};// Extend our default options with those provided.var opts = $.extend(defaults, options);// Our plugin implementation code goes here.};
Our plug-in can be called as follows:
$('#myDiv').hilight({foreground: 'blue'});
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 with less code.
And modify the plug-in. Next we start to use function objects.
// plugin definition$.fn.hilight = function(options) {// Extend our default options with those provided.// Note that the first arg to extend is an empty object -// this is to keep from overriding our "defaults" object.var opts = $.extend({}, $.fn.hilight.defaults, options);// Our plugin implementation code goes here.};// plugin defaults - added as a property on our plugin function$.fn.hilight.defaults = {foreground: 'red',background: 'yellow'}
Now users can include a line like this in their scripts:
// This only needs to be called once, and it is not necessary to call $. fn. hilight. defaults. foreground = 'blue' in the ready block ';
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 select
Overwrite these new default values
// Overwrite the Default background color of the plug-in $. fn. hilight. defaults. foreground = 'blue ';//... // call the plug-in with a new default setting $ ('. hilightDiv '). hilight ();//... // pass the configuration parameters to the plug-in method to overwrite the default setting $ ('# 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,
In our plug-in implementation, we can define a function named "format" to format the highlighted text. Our plug-in now looks like this,
The implementation of the default format method is under the hiligth function.
// plugin definition$.fn.hilight = function(options) {// iterate and reformat each matched elementreturn this.each(function() {var $this = $(this);// ...4var markup = $this.html();// call our format functionmarkup = $.fn.hilight.format(markup);$this.html(markup);});};// define our format function$.fn.hilight.format = function(txt) {return '' + txt + '';};
We can easily support other attributes in the options object by allowing a callback function to overwrite the default settings. This is another
An excellent way to modify your plug-in. The trick shown here is to further effectively expose the format function so that it can be redefined. Through this
The trick is that 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 Cycle.
Plug-in. This Cycle plug-in is a slide display plug-in that supports many internal transformations, such as scrolling, sliding, and gradient disappearance. But the actual
There is no way to define the effects that may be applied to slide changes. That is where this scalability is useful. Use the Cycle plug-in
Expose the "transitions" object so that they can add their own transformation definitions. The plugin is defined 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 attacked
Exposure, you need to maintain any changes to the parameters or semantics in your mind may undermine backward compatibility. It is reasonable to say that if you cannot
Determine whether to expose specific functions, so 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
Will add another "debug" function to our plug-in. This debug function will output the selected element format to firebug control.
. To create a closure, we define the entire plug-in as a function.
(function($) {// plugin definition$.fn.hilight = function(options) {debug(this);// ...};// private function for debuggingfunction debug($obj) {if (window.console && window.console.log) window.console.log('hilight selection count: ' + $obj.size());};// ...})(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 plug-in options with a small number of "markup" (this is very useful when creating an example ). And support it
Very simple. Update: There are some optimization suggestions in the comments.
$.fn.hilight = function(options) {// ...// build main options before element iterationvar opts = $.extend({}, $.fn.hilight.defaults, options);return this.each(function() {var $this = $(this);// build element specific optionsvar o = $.meta ? $.extend({}, opts, $this.data()) : opts;//...
These change lines do something: it is to test whether the Metadata plug-in is installed
If it is installed, it can extend our options object by extracting metadata
This line is added to JQuery. extend as the last parameter, so it will overwrite any other option settings. Now we can start from "markup"
If we select "markup ":
Have a nice day!Have a nice day!Have a nice day!
Now we can highlight which divs only use one line of script:
$('.hilight').hilight();
2.7 Integration
The code after the example is completed is as follows:
// Create a closure (function ($) {// plug-in definition $. fn. hilight = function (options) {debug (this); // build main options before element iterationvar opts = $. extend ({}, $. fn. hilight. defaults, options); // iterate and reformat each matched elementreturn this. each (function () {$ this = $ (this); // build element specific optionsvar o = $. meta? $. Extend ({}, opts, $ this. data (): opts; // update element styles+this.css ({backgroundColor: o. background, color: o. foreground}); var markup = descrithis.html (); // call our format functionmarkup = publish (markup) ;}; // Private function: debuggingfunction debug ($ obj) {if (window. console & window. console. log) window. console. log ('hilight selection count: '+ $ obj. size () ;}; // defines the exposure format function $. fn. hilight. format = function (txt) {return''+ Txt +'';}; // Defaults $ of the plug-in. fn. hilight. defaults = {foreground: 'red', background: 'yellow'}; // closure end}) (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
It is more convenient to understand the concept of a class. JQuery is a well-encapsulated class. For example, we use statements
$ ("# Btn1") generates an instance of the jQuery class.
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. Yes.
Do:
$. 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, it implements the extension.
When it is clicked, the content in the current edit will pop up 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:
$.extend({add:function(a,b){return a+b;}});
Add a "static method" for jQuery as add. Then, you can use this method when introducing jQuery.
Method, $. add (3, 4); // return 7