Learn jquery plugin development from scratch

Source: Internet
Author: User
Tags beautifier

Http://www.w3cfuns.com/notes/19462/ec18ab496b4c992c437977575b12736c.html

The most successful part of JQuery is its extensibility, which has created an ecosystem by attracting many developers to add functionality.

There are three main ways to develop jquery plugins:

    • Extend jquery with $.extend ()
    • Add a new method to jquery through $.fn
    • Created using the part factory method of the jquery UI by $.widget ()



Usually we use the second method for simple plug-in development,
The third way is to develop more advanced jquery parts, the model developed by the parts with a lot of jquery built-in features, such as plug-in state information automatically saved, a variety of plug-ins commonly used methods, not in detail here.

The first way is to add a static method to the jquery namespace (or to jquery) by calling the function that was added via $.extend () directly through the $ symbol call ($.myfunction ()) without having to check the DOM element ($ (' # Example '). MyFunction ()).

For example:

$.extend ({
Sayhello:function (name) {
Console.log (' Hello, ' + (name Name: ' Dude ') + '! ');
}
})
$.sayhello (); Call
$.sayhello (' wayou '); Call with parameter

But this approach does not take advantage of jquery's powerful selectors, the need to work with DOM elements and to better apply the plug-in to selected elements, or to use the second development approach.



the second way of jquery plugin development

First look at its basic format:

$.fn.pluginname = function () {
Your code goes here
}

This is to add a method to $.fn above, Pluginname is our plug-in name.

For example, if we turn all the link colors on the page to red, we can write this plugin:

$.fn.myplugin = function () {
In this case, this refers to the element selected with jquery.
Example: $ (' a '), then this=$ (' a ')
This.css (' Color ', ' red ');
}

Inside this function, this refers to the element that the jquery selector selects when we call the plug-in. For example, $ (' a ') returns a collection of all a tags on the page, and the collection is already a jquery wrapper type, which means that other methods of jquery can be called directly when manipulating it without the need for the $ symbol wrapper.

So in the example above, this call to JQuery's CSS () method is equivalent to calling $ (' a '). css ().

It is important to understand this. So you know why you can use the JQuery method at the same time and in other places this is not the same time we need to re-wrap in jquery to invoke.

can now go to the page to try out our code, put a few links on the page, call the plugin after the link font into red.

<ul>
<li>
<a href= "Http://www.webo.com/liuwayong" > My Weibo </a>
</li>
<li>
<a href= "http://http://www.cnblogs.com/Wayou/" > My blog </a>
</li>
<li>
<a href= "http://wayouliu.duapp.com/" > My station </a>
</li>
</ul>
<p> This is P tag is not a label and I will not be affected </p>
<script src= "Jquery-1.11.0.min.js" ></script>
<script src= "Jquery.myplugin.js" ></script>
<script type= "Text/javascript" >
$ (function () {
$ (' a '). Myplugin ();
})
</script>

Operation Result:



Further, each specific element is processed in the plug-in code instead of a collection, so that we can operate on each element accordingly.

In the above mentioned this refers to the collection returned by the jquery selector, then each element of the collection can be processed by invoking the. each () method of jquery, but at this point it is important to note that within each method, this is no longer a jquery object. Instead of a normal DOM object, if you call jquery's method, you need to wrap it before you can call it.

For example, now we want to show the real address of the link in each link, first through each of the a tags, and then get the value of the HREF attribute and add to the link text behind.

After the change our plug-in code is:

$.fn.myplugin = function () {
In this case, this refers to the element selected with jquery.
This.css (' Color ', ' red ');
This.each (function () {
Working with each element
$ (this). Append (' "+ $ (This). attr (' href '));
}))
}


The calling code is still the same, we call this plugin by selecting all the a tags on the page

Operation Result:



Now, you can write a simple jquery plugin.

The following starts the jquery plugin to write an important part of the parameter reception.

supports chained calls

We all know that jquery. An elegant feature is the ability to support chained calls and to invoke other methods continuously after selecting a good DOM element.

To make the plug-in not break the chain call, just return it.

$.fn.myplugin = function () {
In this case, this refers to the element selected with jquery.
This.css (' Color ', ' red ');
Return This.each (function () {
Working with each element
$ (this). Append (' "+ $ (This). attr (' href '));
}))
}


Let the plug-in receive parameters

A strong plugin can be customized by the user, which requires us to write the plug-in to receive the appropriate parameters provided.

For example, we don't want the link to turn red, we let the user of the plugin define what color to display, requiring the user to pass in a parameter when the call is made. We receive the code inside the plugin. If the user does not pass the parameter, the plug-in will give the default value of the parameter. The

typically uses the Extend method of jquery to handle the receipt of plug-in parameters. When the Extend method passes a single object, the object is merged into jquery, and when you pass more than one argument using the Extend method, it merges all the parameter objects into the first one. At the same time, if the object has the same name attribute, then the merge will overwrite the previous one.

With this, you can define an object in the plug-in that holds the default value of the plug-in parameter, merge the received parameter object onto the default object, and finally implement the user-specified value parameter with the specified value, using the plug-in default value for unspecified parameters.

For example, here you specify a parameter, FontSize, that allows you to set the font size when the plug-in is called.

$.fn.myplugin = function (options) {
var defaults = {
' Color ': ' Red ',
' FontSize ': ' 12px '
};
var settings = $.extend (defaults, options);
Return This.css ({
' Color ': Settings.color,
' FontSize ': settings.fontsize
});
}

Now, we call the time to specify the color, the font size is not specified, will be used in the plug-in default value 12px

$ (' a '). Myplugin ({
' Color ': ' #2C9929 '
});

Operation Result:



Specify both color and font size:

$ (' a '). Myplugin ({
' Color ': ' #2C9929 ',
' FontSize ': ' 20px '
});

Operation Result:




The above code will change the value of defaults when calling extend, and if you want to use defaults in subsequent code, you will see that it has been changed by the user's passed in parameter. However, for plug-ins, the value of defaults should not be changed.



So, a new empty object is taken as the first parameter of $.extend, and defaults and the parameter object passed by the user are immediately followed so that all values are merged onto the empty object, protecting the default values in the Defaults object inside the plug-in.

$.fn.myplugin = function (options) {
var defaults = {
' Color ': ' Red ',
' FontSize ': ' 12px '
};
var settings = $.extend ({},defaults, options);//Use an empty object as the first argument
Return This.css ({
' Color ': Settings.color,
' FontSize ': settings.fontsize
});
}

After the plug-in can receive and process the parameters, it is possible to write out more robust and flexible plugins. To write a complex plug-in, the amount of code will be very large, how to organize the code is a need to face the problem, there is no good way to organize the code, the overall feeling will be disorganized, but also not good maintenance, so the plug-in all the method properties wrapped to an object, with object-oriented thinking to develop, Will undoubtedly make the work much easier.

Object-oriented plug-in development

The concept and importance of object-oriented programming is no longer elaborated. For plug-in development, why use object-oriented thinking.

Suppose you do not, when you need a method to define a function, when you need another method, then to define a function, without rule to define some scattered in the code everywhere variables and methods, the structure is not clear, maintenance is not convenient.

Suppose you use object-oriented thinking to design a plug-in, define the important variables you need into the object's properties, the function becomes the method of the object, one is easy to manage, and the other does not affect the external namespace, because all of these variable names have method names inside the object.

Then the above example, his function is to set the color Ah font ah what, we can put this plugin into a beautification of the Page object, we can also add other functions, such as setting the underline or something.

So we create a new object named Beautifier, and then we use this object in the plugin to encode it.

To define the Beautifier constructor
var beautifier = function (Ele, opt) {
this. $element = Ele,
This.defaults = {
' Color ': ' Red ',
' FontSize ': ' 12px ',
' textdecoration ': ' None '
},
This.options = $.extend ({}, this.defaults, opt)
}
Methods for defining Beautifier
Beautifier.prototype = {
Beautify:function () {
return this. $element. css ({
' Color ': This.options.color,
' FontSize ': this.options.fontSize,
' TextDecoration ': this.options.textDecoration
});
}
}
Using the Beautifier object in a plug-in
$.fn.myplugin = function (options) {
Create a Beautifier entity
var beautifier = new Beautifier (this, options);
Call its method
return beautifier.beautify ();
}

Through the above transformation, our plug-in has become object-oriented, better maintenance and understanding. To add new functionality in the future, you only need to append a new variable and method to the object, and then instantiate it in the plugin to invoke the newly added item.

Plug-in calls are the same, our changes to the code do not affect the rest of the plugin, but the organization of the Code to change the structure.

$ (function () {
$ (' a '). Myplugin ({
' Color ': ' #2C9929 ',
' FontSize ': ' 20px '
});
})




Specifies that the text is underlined (the new feature we added in the Beautifier object, which is not underlined by default, as in the example above):

$ (function () {
$ (' a '). Myplugin ({
' Color ': ' #2C9929 ',
' FontSize ': ' 20px ',
' textdecoration ': ' Underline '
});
})




Here, you can better write complex plugins and organize your code well. When we look back at the code above, there is still room for improvement. Here are some miscellaneous things about namespaces and variables.

name Space

One thing we should be aware of when writing any JS code is thatdo not pollute the global namespace。 Because with the increase of your code, if you always define some variables in the global scope, it is difficult to maintain it at last, and it is easy to conflict with the code written by others.

For example, you add a variable status to the Global window object in your code, the page references another library that someone else wrote, and you add a variable of the same name to the global, and the final result is definitely a conflict. So, in general, we don't define variables as global, unless we have to.

A good practice is to always wrap your code with self-invoking anonymous functions so that you can safely use it anywhere,There is absolutely no conflict.

Wrap your code with self-invoking anonymous functions

We know that JavaScript cannot be used to create scopes in curly braces, and that code within a domain cannot be accessed by outsiders. If we put our own code in a function, it doesn't pollute the global namespace, and it doesn't conflict with other code.

Above we define a beautifier global variable, which will be attached to the global Window object, how to prevent this kind of thing happen?

One solution is to put all the code in the jquery plug-in definition code, which is put into $.fn.myplugin. But this makes the code for our plugin definitions bloated, and in $.fn.myplugin we should focus more on plug-in calls and interaction with jquery.

Another workaround is to wrap all the code with a self-invoking anonymous function.

(function () {
To define the Beautifier constructor
var beautifier = function (Ele, opt) {
this. $element = Ele,
This.defaults = {
' Color ': ' Red ',
' FontSize ': ' 12px ',
' textdecoration ': ' None '
},
This.options = $.extend ({}, this.defaults, opt)
}
Methods for defining Beautifier
Beautifier.prototype = {
Beautify:function () {
return this. $element. css ({
' Color ': This.options.color,
' FontSize ': this.options.fontSize,
' TextDecoration ': this.options.textDecoration
});
}
}
Using the Beautifier object in a plug-in
$.fn.myplugin = function (options) {
Create a Beautifier entity
var beautifier = new Beautifier (this, options);
Call its method
return beautifier.beautify ();
}
})();

The benefits of doing so are in addition to those described above. Another benefit is that the code from the invocation of the anonymous function will be executed in the first time, and after the page is ready, the code above will be ready to use the plug-in in later code.

So far it seems to be close to perfection . If we consider other factors, such as putting this code on the page, the previous code did not end with a semicolon, or the previous code changed the system variables or keywords, such as window, undefined, and so on, just as we used in our own code, The result is unpredictable, and that's not what we want.

passing system variables to the inside of the plug-in as variables

What is the result of the following code?

var foo=function () {
Someone else's code
}//notice there's no semicolon ending here.

Start our code ...
(function () {
Our code:
Alert (' hello! ');
})();

Originally other people's Code also works, but the last definition of the function is not terminated with a semicolon, and then when the page introduced our plug-in, the error, the code does not execute properly.

The reason is that the first pair of parentheses we use to act as a self-invoking anonymous function is connected to a function defined above, because there is no semicolon in the middle, our code does not parse properly, so error.

So the good thing is that we add a semicolon at the beginning of the code, which is a good habit at all times.

var foo=function () {
Someone else's code
}//notice there's no semicolon ending here.

Start our code ...
;(function () {
Our code:
Alert (' hello! ');
})();

At the same time, it is a good practice to pass system variables in the form of parameters to the inside of the plug-in.

When we do this, system variables such as window have a local reference within the plug-in, which improves access speed and provides some performance improvements.

Finally we get a very safe and well-structured code:

;(function ($,window,document,undefined) {
Our code:
blah blah blah ...
}) (jquery,window,document);


And as for this undefined, it is very interesting, in order to get unmodified undefined, we did not pass this parameter, but received it when received, because the actual is not transmitted, so ' undefined ' that position received is the real ' Undefined ' out. It is a technology and a way of thinking that deserves to be understood, and of course not invented by me, but learned from previous experience.

So in the end our plugin became this:

;(function ($, window, document,undefined) {
To define the Beautifier constructor
var beautifier = function (Ele, opt) {
this. $element = Ele,
This.defaults = {
' Color ': ' Red ',
' FontSize ': ' 12px ',
' textdecoration ': ' None '
},
This.options = $.extend ({}, this.defaults, opt)
}
Methods for defining Beautifier
Beautifier.prototype = {
Beautify:function () {
return this. $element. css ({
' Color ': This.options.color,
' FontSize ': this.options.fontSize,
' TextDecoration ': this.options.textDecoration
});
}
}
Using the Beautifier object in a plug-in
$.fn.myplugin = function (options) {
Create a Beautifier entity
var beautifier = new Beautifier (this, options);
Call its method
return beautifier.beautify ();
}
}) (JQuery, window, document);


A secure, well-structured, organized plug-in was written .

Learn jquery plugin development from scratch

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.