jquery plugin classification, writing and example

Source: Internet
Author: User
Tags jquery library

There are 2 main types of 1.jQeury

1) The Instance object method plug-in develops methods that enable all jquery instance objects to be called. In other words, as long as the $ () factory gets
jquery instance object, you can call the method we developed. 95% of all plugins are of this type

2) The global function plug-in can add independent functions to the jquery namespace. Then you can use the $. Function name when calling
Called () or jquery. The function name () is called. Can be understood as static methods.

2. Add a global function
We can understand jquery as a class, and $ is the alias of this class. Developing a global function is the development of this class
static methods. such as $.get (), $.post (). Adding a new global function is actually extending the jquery "class" itself,
Give the jquery namespace a place to contribute.

Adding the name of the newly added global function is SayHello, and the function is to pop up a Hello dialog box.

2.1 Adding a global function
jquery.sayhello=function(name) {alert ("Hello," +name);}
Call:
$.sayhello (' Zhang San ');
Or
Jquery.sayhello ("John Doe");
2.2 Adding multiple global functions
Use the global function extend provided by jquery to join multiple functions at once
jquery.extend ({sayHello:function(name) {         alert ("Hello" +name);},saybye: function (name) {         alert ("good-bye" +

The above code adds two functions SayHello and Sybye to the jquery namespace, calling the same as

2.3 Namespaces

The previous approach is likely to have a risk of naming conflicts with other functions in the jquery namespace, and it is possible
Same name as the methods defined in other jquery plugins, so we can consider encapsulating all of our defined functions
To an object, which is equivalent to giving our function a namespace.

The code is as follows:
jquery.wq={sayHello:function(name) {         alert ("Hello" +name);},saybye:  function(name) {         alert ("good-bye" +name);}}

This is how this can be understood: first we add a Wq property to jquery, and this property
Body is an object, and later we use JSON to define an object that has two methods.

So the call is in the following form:
Call:
$.wq.sayhello ("Harry"); JQuery.wq.sayBye ("Zhao Liu")

Note: Even if the page contains a jquery file, you should not assume that the abbreviated form "$" is always valid.
Because "$" is just an alias, other libraries can redefine the "$". So when you define a plugin,
It is best to use jquery to invoke the method, or redefine "$"

3. Create a new method for the jquery instance object
Extends the methods in all of the jquery instance objects.
3.1 Define one method at a time
jquery.fn.sayhello=function() {alert ("Hello!") );} Call: $ ("div"). SayHello ();

3.2 Define more than one method at a time
The previous definition of a method is too few, can we define a number of methods at a time? The jquery library provides
JQuery.fn.extend method to define multiple methods at once
jQuery.fn.extend ({sayHello:function() {         alert ("Hello");},saybye:  function() {         alert ("Bye Bye");}});
You can see that the parameters of the Extend method are actually a JSON-formatted object.
The call can be called as follows:

4. Description of the This keyword inside the plug-in method
The above notation is equivalent to every jquery instance, which is no different from a global function. The instance methods we define are often required to be used in a particular environment. So when we write the plug-in method, we should consider the environment of the object method. The "This" keyword refers to the current jquery instance object within any plug-in method. Therefore, any jquery method can be called on this. It is important to note that the jquery selector we are using may have multiple elements selected, and the "current jquery instance" could be an element, multiple elements, or 0 elements. We must consider this situation.

If we use selectors to select multiple elements, we can use the each () method to iterate over each element, within each method, and then use this, which refers to a reference to each HTML DOM element.

5. Method concatenating
When using the JQuery object method, you can basically use the concatenating approach. Then we must return a jquery instance object for the plug-in method when we use the plugin.
jQuery.fn.extend ({sayHello:function() {     alert ("Hello");      return  This ;},saybye:function() {     alert ("Bye Bye");      return  This ;}});

6. Defining default values for plug-in methods

By using the Jquery.extend () method, you can conveniently provide default values that can be overwritten by parameters that are passed in at any time, and the call to the method will remain approximately the same.

Note: The Jquery.extend method is available in two places in the API, one in the "core". "Plug-in mechanism", and only one parameter. One in "Tools". "Array and object operations."

Note Here we are using the latter, in the form: Jquery.extend (target, Object1)

Its purpose is to copy all the properties and methods from subsequent objects into the preceding object, and to copy the properties and methods in the Object1 to the target object.

So when we define a plugin, we can specify the default value for the plug-in method in the following ways:
jquery.fn.sayhello=function(properties) {var defaults={     name:"Zhang San", Age     :};jquery.extend (defaults,properties); alert ("first argument:" +defaults.name+ "second argument" +  Defaults.age); return  This ;}

so that we can call the
$ ("div"). SayHello ({    name: "John Doe",    age:30});

  

or:
$ ("div"). SayHello ({    name: "Harry"});

  

or:
$ ("div"). SayHello ({    age:25});

  

7. Plug-in development tips-closures
We are in the process of developing the plug-in, the code is written in a JS file, then this JS file may define a lot of methods or some variables. Then these methods or variables may conflict with other JS file variables or methods, then how can we define the JS code "exposed" part of the hidden part of it? That is, although you define, but in other places do not access, the exposure of the exposed, should not be exposed to hide, to achieve this goal, you need to use the "closure"

What is "closure"? The simple point is that an intrinsic function is allowed, that is, to define another function in the function, and that the intrinsic function can access the variables and other intrinsic functions declared in the outer function. For example, there are the following definitions:
// Define a function function A () {// define B function var b=function() {alert ("This is B");} return // returns the B function }var c=a (); // at this point C is the B function C (); // actually, it's called the B function .

As you can see, the inner function B executes outside the A function that contains it, which forms the closure. That is, B is executed after the external function a returns, and when B executes it can still access the local variables and other intrinsic functions defined in a.

Using the characteristics of closures, we can expose the methods we need to expose, such as B, we can hide some local variables and functions, such as defining variables and functions in a, other functions other than a are inaccessible, but B can be accessed.

In fact, the above code is to execute a function first, get the result, the result is a function, and then execute the B function is

  

since our goal is to get B to execute outside a, we can make the following modifications to the code:
var C; function A () {var b=function() {     alert ("This is the B function");} C=b; // assigning an intrinsic function to C }// let a function execute, after a executes, B is assigned to CA (); // now execute C, which is actually executing B (); //

can you get a to execute immediately after the definition? We can define an anonymous function to put in a pair of parentheses, and then
Then execute it with a pair of parentheses:
var C; ( function () {var b=function() {alert ("This is a B function");} C=b; // assigning an intrinsic function to C })()//



Can you pass a parameter from outside and give it to function B? Rewrite the code as follows:
(function($) {// ) Here you can use the $ symbol ..... // Add the B function to the instance object function of jquery $.fn. b=function() {     alert ("This is b function");}}) (jQuery);

This code is loaded by the browser will be executed, jquery as a parameter passed in to the $ symbol, so the inside can use the $ symbol, in the code, we use $.FN for the instance of jquery to add a method B, the page used:
<script>$ (document). Ready (function() {    $ ("H1"). B ();}); </script>

Execution results
So the common jquery plug-ins are in the following form:
The benefit is that the code is internally defined in a way that only plug-ins can access, which hides some code, exposing the exposed plug-in method to the outside part.
(function ($) {//Plugin code}) (JQuery)

  

JS plug-in development of a method:JS Code:
<script type= "Text/javascript" src= "jquery-1.9.1.min.js" ></script><script type= "Text/javascript" >(function ($) {//default parameters (placed outside the plugin to avoid calling the plug-in every time, saving memory)varDefaults ={color:Red};//Extended$.fn.extend ({//plug-in nameHeightfunction(options) {//overriding default parametersvaropts =$.extend (defaults, options);//Main functionreturn  This. each (function () {//Activation Eventsvarobj = $ ( This); Obj.click (function() {alert (opts.color);})}) (jQuery); $ (function () {$("P"). Height ({color: ' black ' });});</script>

transferred from: http://www.360doc.com/content/14/0307/09/15605563_358431371.shtml

JQuery Plugin classification, authoring, and instance

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.