JQuery Plugin Development Full analysis

Source: Internet
Author: User

There are two types of jquery plugin development:
One is the development of a class-level plug-in that adds a new global function to jquery, which is equivalent to adding a method to the jquery class itself. Jquery
Global functions are functions that belong to the jquery namespace, and the other is an object-level plug-in development that adds a method to a jquery object. Under
The development of two kinds of functions is described in detail.
1, class-level plug-in development
The most straightforward understanding of plug-in development at the class level is to add a class method to the jquery class, which can be understood as adding a static method. A typical example is
is $. The AJAX () function, which defines the function in the jquery namespace. Plug-in development at the class level can be implemented in the following ways
Line extension:
1.1 Adding a new global function
To add a global function, we just need to define the following:

Jquery.foo = function () {<span style= "White-space:pre" ></span>alert (' This is a test. This was only a test. ');
The call can be written like this: Jquery.foo (); or $.foo ();

1.2 Adding multiple global functions
Add multiple global functions, which can be defined as follows:

Jquery.foo = function () {<span style= "White-space:pre" ></span>alert (' This is a test. This was only a test. '); Jquery.bar = function (param) {<span style= "White-space:pre" ></span>alert (' This function takes a parameter, Which is "' + param + '". ');
Called when it is the same as a function: Jquery.foo (); Jquery.bar (); or $.foo (); $.bar (' Bar ');

1.3 Using Jquery.extend (object);

Jquery.extend ({<span style= "White-space:pre" ></span>foo:function () {<span style= "White-space:pre" ></span>alert (' This is a test. This was only a test. '); <span style= "White-space:pre" ></span>},<span style= "White-space:pre" ></span>bar:function (param) {<span style= "White-space:pre" ></span>alert (' This function takes a parameter, which is "' + param + '".); <span style= "White-space:pre" ></SPAN>});

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 still inevitably some
Some functions or variable names conflict with other jquery plugins, so we are accustomed to encapsulating some methods into another custom namespace.

Jquery.myplugin = {<span style= "White-space:pre" ></span>foo:function () {<span style= "White-space:pre "></span>alert (' This is a test. This was only a test. '); <span style= "White-space:pre" ></span>},<span style= "White-space:pre" ></span>bar:function (param) {<span style= "White-space:pre" ></span>alert (' This function takes a parameter, which is "' + param + '".); <span style= "White-space:pre" ></span>}};
The function that takes the namespace is still the global function, the method that is used when calling:


$.myplugin.foo (); $.myplugin.bar (' Baz ');

With this technique (using a separate plug-in name), we can avoid collisions of functions within namespaces.


2, Object-level plug-in development
Plug-in development at the object level requires two forms:,
Form 1:

(function ($) {$.fn.extend ({pluginname:function (OPT, callback) {//Our plugin implementation code goes here.})}) (JQuery);

Form 2:

(function ($) {$.fn.pluginname = function () {//Plugin implementation code goes here};}) (JQuery);

The above defines a jquery function, the parameter is $, and after the function definition is complete, the jquery argument is passed in. Call execution immediately.
The advantage of this is that when we write a jquery plugin, we can also use this alias, without causing a conflict with prototype.
2.1 Declare a name under the jquery namespace
This is a single plug-in script. If your script contains multiple plugins, or an inverse plug-in (for example: $.fn.dosomething ()
and $.fn.undosomething ()), then you need to declare multiple function names. However, when we write a plugin, we strive to only
Use a name to contain all of its contents. Our example plug-in is named "Highlight"

$.fn.hilight = function () {//We plugin implementation code goes here.};

Our plug-in is called by this way:

$ (' #myDiv '). Hilight ();

But what if we need to decompose our implementation code into multiple functions? There are many reasons: design needs; it's easier to do that.
Or more readable implementations, and this is more consistent with object-oriented. This is a real hassle, breaking down functionality into multiple functions without adding extra
namespace. For the sake of recognizing and using functions as the most basic class object in JavaScript, we can do this. Just like other objects,
A function can be specified as a property. So we have declared "Hilight" as the Property object of jquery, any other property or function we
The attribute can be declared in the "hilight" function if it needs to be exposed. Continue later.

2.2 Accept the options parameter to control plug-in behavior
Let's add features to our plug-in to specify the foreground and background colors. We might have the option to pass it like an options object to
Plug-in functions. For example:

Plugin definition$.fn.hilight = function (options) {var defaults = {foreground: ' Red ', background: ' Yellow '};//Extend ou R default options with those Provided.var opts = $.extend (defaults, options);//Our plugin implementation code goes here.} ;

Our plug-in can be called this way:

$ (' #myDiv '). Hilight ({foreground: ' Blue '});

2.3 Exposing the default settings for plugins
One of the improvements we should take with the above code is to expose the plugin's default settings. This makes it easier for plug-in users to overwrite with less code
and modify the plugin. Next we start using the function object.

Plugin definition$.fn.hilight = function (options) {//Extend our default options with those provided.//Note that the F Irst arg to extend is a empty object-//this was 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 in our plugin Function$.fn.hilight.defaults = {foreground: ' Red ', background: ' Yell Ow '}

Now the user can include a line like this in their script:

This only needs to be called once and does not necessarily call $.fn.hilight.defaults.foreground = ' Blue ' in the Ready block;

Next we can use the plug-in method like this, 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 in the plugin's default foreground color. And users still have a choice when they need it.
Overwrite these new default values

Overwrite the default background color of the plugin $.fn.hilight.defaults.foreground = ' blue ';////...//Use a new default setting to call the plug-in $ ('. Hilightdiv '). Hilight ();//...// Override the default setting of $ (' #green ') by passing configuration parameters to the plug-in method. Hilight ({foreground: ' green '});

2.4 Appropriate exposure to some functions
This section will step-by-step to the previous code by extending your plugin in an interesting way (while letting others expand 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,
The implementation portion of the default format method is below the Hiligth function.

Plugin definition$.fn.hilight = function (options) {//iterate and reformat each matched Elementreturn This.each (functio N () {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 ' <strong> ' + txt + ' </strong> ';};

It's easy to support other properties in the options object by allowing a callback function to override the default settings. This is the other one.
A great way to modify your plugin. The technique shown here is to further effectively expose the format function so that he can be redefined. Through this
The trick is that other people can pass their own settings to overwrite your plugin, in other words, so that other people can also write plugins for your plugin.
Considering the useless plugins we've created in this article, you might want to know when it's going to be useful. A real example is the cycle
Plug-ins. This cycle plugin is a sliding display plugin that allows many internal transformations to scroll, slide, fade, and so on. But the actual
, there is no way to define the effect that may apply to each type of slide change. That's where extensibility is useful. Cycle plug-in to use
The "Transitions" object is exposed so that they add their own transformation definitions. The plugin defines it like this:

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

This technique enables others to define and transfer the transform settings to the cycle plugin.

2.5 Keeping private functions private
This technique exposes a part of your plugin to be overwritten is very powerful. But you need to think carefully about the parts of your implementation that are exposed. One but was violently
You need to keep any changes to the parameters or semantics in your mind may undermine backwards compatibility. A thong is if you can't be willing to
Specific functions are exposed, you may not need to do that.
So how do we define more functions without cluttering up namespaces and not exposing implementations? This is the function of the closure. To demonstrate, we will
Will add another "debug" function to our plugin. This debug function will output the selected element format to the Firebug control
Console In order to create a closure, we will wrap the entire plug-in definition in a function.

(function ($) {///Plugin definition$.fn.hilight = function (options) {debug (this);//...};//Private function for debugging function Debug ($obj) {if (window.console && window.console.log) window.console.log (' Hilight selection count: ' + $obj. Size ());};/ / ...}) (JQuery);

our "Debug" method cannot be entered from outside closures, so it is private to our implementation.
2.6 Support Metadata Plugin
On the basis of the plugin you are writing, adding support for the metadata plugin will make him more powerful. Personally, I like this.
Metadata plugin, because it allows you to use a few "markup" overlay plugin options (this is useful when creating an example). and support it.
Very simple. Update: Comments have a bit of tuning recommendations.

$.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? $.e Xtend ({}, OPTs, $this. Data ()): opts;//...

These changes do something: it's testing whether the metadata plugin is installed
If it is installed, it can expand our options object by extracting the meta data
This line is added as the last parameter to Jquery.extend, then it overrides any other option settings. Now we can get from "markup"
Drive behavior If we select "Markup":

<!--markup--><div class= "hilight {background: ' Red ', foreground: ' White '}" >have a nice day!</div>< ;d IV class= "hilight {foreground: ' Orange '}" >have a nice day!</div><div class= "hilight {background: ' green ' } ">have a nice day!</div>

Now we can highlight which Div uses only one line of script:

$ ('. Hilight '). Hilight ();

2.7 Integration
Here's the code to get our example done:

Create a closure (function ($) {///plug-in definition $.fn.hilight = function (options) {debug (this);//build main options before element iteratio Nvar opts = $.extend ({}, $.fn.hilight.defaults, options);//iterate and reformat each matched Elementreturn This.each (func tion () {$this = $ (this);//build element specific Optionsvar o = $.meta? $.extend ({}, OPTs, $this. Data ()): opts;//updat e element styles$this.css ({backgroundcolor:o.background,color:o.foreground}); var markup = $this. HTML ();//Call our Format Functionmarkup = $.fn.hilight.format (markup); $this. HTML (markup);});};/ /Private Function: Debuggingfunction debug ($obj) {if (window.console && window.console.log) window.console.log (' Hilight Selection count: ' + $obj. Size ());};/ /define exposure Format Function $.fn.hilight.format = function (txt) {return ' <strong> ' + txt + ' </strong> ';};/ /Plugin Defaults$.fn.hilight.defaults = {foreground: ' Red ', background: ' Yellow '};//closure} ' (JQuery);

This design has allowed me to create a powerful plug-in that conforms to specifications. I hope it will help you to do the same.

3. Summary
jquery has two methods for developing plug-ins, namely:
JQuery.fn.extend (object); Adds a method to a 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's the FN thing? If you look at 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
The concept of a definite class, but it is more convenient to use a class to understand it. jquery is a very well-encapsulated class, such as 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.
An instance of the jquery class can use this "member function".
For example, we want to develop a plugin, make a special edit box, when it is clicked, then alert the contents of the current edit box. Can this
What do you do:

$.fn.extend ({alertwhileclick:function () {$ (this). "Click (function () {alert (this). Val ());});}); $ ("#input1"). Alertwhileclick (); On the page: <input id= "INPUT1" type= "text"/>

$ ("#input1") is a jquery instance, and when it calls the Member method Alertwhileclick, it implements the extension, each time
When Clicked, it pops up the contents of the current edit.
3.2 Jquery.extend (object);
Adding a class method to the jquery class can be understood as adding a static method. such as:

$.extend ({<span style= "White-space:pre" ></span>add:function (A, b) {return a+b;}});

adds a "static method" for jquery to add, which can then be used where jquery is introduced.
Law, $.add (3,4); Return 7

JQuery Plugin Development Full analysis

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.