jquery Plugin Development (RPM)

Source: Internet
Author: User

While browsing the CodeProject website, I suddenly saw an article: how to write plugin in Jquery.
If the E-text good classmate, you can see the above connection.
Now I write this article on the above website and the combination of my own ideas. Hope to get the support and understanding of Daniel ... The Big Bird flies over ... Welcome to the dress.
Source:

"1" How to write plugin in Jquery.

"2" a sharp jquery book

"3" Rascallysnake's Jquery.extend () detailed
I. Introduction
The purpose of the plug-in is to provide an encapsulation of a series of methods or functions that are already in place, so that they can be reused elsewhere to facilitate later maintenance.
In addition to providing a simple and efficient way to manage elements and scripts, jquery also provides an exception to the mechanism of adding its own methods and additional functionality to the core modules.

With this mechanism, jquery allows us to create our own plugins to improve our efficiency in the development process.

1.1 jquery plugins are divided into 3 types:
(1) Plug-in for encapsulating object methods (i.e., object-level development)
This type of plugin is the plugin we need to talk about today.
(2) Plug-in for encapsulating global functions (class-level development)
Refers to the ability to add separate functions under the jquery namespace.
To add a global function, we just need to define the following:
Jquery.foo = function () {
Alert (' This is a test. This was only a test. ');
};
Of course you can also add multiple global functions:

function () {alert (' This is a test. This was only a test. '  function(param) {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 ');
(3) Selector plug-in


1.2 What to note about writing jquery plugins:
(1) The recommended naming method for plug-ins is: jquery. [Plugin name].js
(2) All object methods should be attached to the Jquery.fn object, and all global functions should be appended to the JQuery object itself.
(3) Inside the plug-in, this is the jquery object currently fetched through the selector, and unlike the normal method, the internal this point is the DOM element.
(4) All elements can be traversed by This.each
(5) All methods or function plug-ins should end with a semicolon, or the problem may occur when compressing. To be more insured, you can add a semicolon (;)to the plugin's head to prevent their irregular code from affecting the plugin.
(6) The plugin should return a jquery object in order to ensure the plug-in's chained operation.
(7) Avoid using $ as an alias for jquery objects inside a plug-in, instead use the full jquery to represent it. This avoids conflicts.


1.3JQuery plug-in mechanism
jquery provides 2 ways to extend the functionality of jquery. That
①jquery.fn.extend ()
②jquery.extend ()
The first one is the first of the plug-in types that we said earlier,

The second of the

refers to the following 2 cases.  
Jquery.extend () has an important function in the plug-in to extend an object that already has objects.  
For example:  
var newsrc=$.extend (dest,src1,src2,src3 ...)  
It means to src1,src2,src3 ... Merge into Dest, and the return value is the merged dest, so you can see that the method is merged.  
Example:  
var result=$.extend ({},{name: "Tom", Age:21},{name: "Jerry", Sex: "Boy"})  
Gets the result:  
Result={name: "Jerry", Age:21,sex: "Boy"} 
details can be viewed: jquery.extend function detailed The   has a good explanation for this method.

Official website: jquery.extend () and JQuery.fn.extend ()
use namespace  
Although in the JQuery namespace, We prohibit the use of a large number of JavaScript function names and variable names. However, it is still inevitable that some functions or variable names will conflict with other jquery plugins, so we are accustomed to encapsulating some methods into another custom namespace.

Jquery.myplugin = {foo:function() {alert (' This is a test. This was only a test. '   ); }, Bar:function(param) {alert (' This function takes a parameter, which is "' + param + '".

The function that takes the namespace is still the global function, the method that is used when calling:

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

two. First jquery plugin
If you need to write a jquery plugin, you need to add a property name after the $.fn object, which is actually your plugin name. Its general framework is as follows:

(functionfunction//

Now we need to write the plug-in function is very simple, is to put an object to slowly hide. is to use the fadeout () method.
OK, we open VS 2012. Create a new JScript file and name it: Myplugin.js, and add the following code to it:

(functionfunction  () {  this. FadeOut (' normal ')

How to use it? Very simple.
Create a new HTML page and import the jquery file and just our Myplugin.js file into this page. As follows:

<script type= "Text/javascript" > $ (document). Ready (function  () {$ ("#btn1"). Click ( function () {$ ("#div1"

HTML code:

<div id= "Div1" style= "width:400px; height:30px; Background-color:gray; " > My God

Well, now that you click on the button on the page, the div will slowly hide ... Because we set the normal, it can also set some values and the like.
The excitement is that since this has smart hints, such as:


three. Plug-ins are used in multiple element controls.
3.1 Applied in multiple element controls
The 4th place to note in writing the jquery plugin above is that you can use the This.each method if you want to traverse. $ ("ID"). Each can traverse jquery objects, arrays, and collections.
Ok. Knowing this, our new code looks like this:

(functionfunction  () {  this. each (function  () {$ (  this). Hover ( the function  () {$ (this). AddClass ("Add");}, function  () {$ (this). Removeclass ("Remove"

The. each () method is used primarily for traversal. The code is simple, which is to switch the current object's background-color CSS style to "ADD" and "Remove" directly.

The code for the HTML is:

<div class= "Hovertext" ></div> <div class= "Hovertext" ></div> <div class = "Hovertext" >

JS Code:

<script type= "Text/javascript" > $ (document). Ready (function  () {$ (". Hovertext"

Very simple, not explained.


3.2 Chain Operation
Chained operation? I've heard it all before. For example, the following sentence:
$ ("#div1"). CSS ("Color", "red"). AddClass ("Add"). Animate ({"width": "100px"},1000);
is to be able to implement more operations with "." Behind the current element. This movement is particularly chic.
So how do we achieve this effect? It's easy, I can just get the object back. Note the 6th above: The plugin should return a jquery object in order to guarantee the plug-in's chained operation.
We still look at just the example:

 (function   ($) {$.fn.hoverelement  = function   () { return   This . function   () {$ ( this   function   () {$ ( function   () {$ ( ). Removeclass ("Remove" 

Code is the same, the only difference is: This.each (function () {This is preceded by a return. This enables us to chain-operate.
And then you do:

$ (document). Ready (function  () {$ (". Hovertext"). Hoverelement (). CSS ("Color", "yellow"

Can see the text has become a yellow color.

Four. Customize your own plugins
For a business plug-in, customizing the plugin's style is essential. We can change the developer's default style by entering different styles for ourselves. For example, the most common width, height, url, color, and so on. Without these customizations, the developer-developed plug-in will have a significantly reduced value for use.
OK, the following example means that when we hover an object, it can change its text, background, foreground three properties, that is, the textual, the background color, the foreground color. The user can set the value he wants to set, rather than fixing it to death. Of course, if the user is not set, we will give him a default value.
The development framework for defining such plugins is:
$.fn. Youplugin = function (options) {...}
In order to prevent some lazy people, we need to set some default values, when it is not set, we use these default values.
var defaultval = {
Text: ' Your mouse is over ',
ForeColor: ' Red ',
BackColor: ' Gray '
};
How is the default value combined with the values that the user passes in? This will require the $.extend () knowledge we talked about at the outset.
var obj = $.extend (defaultval, Options);
This way, the user-defined value overrides the default user value. If the user does not define a value, it is customized with the system.
The code is as follows:

(function($) {$.fn.texthover=function(options) {//The options often use this to denote a number of parameters. varDefaultval ={Text:' Your Mouse is over ', ForeColor:' Red ', BackColor:' Gray ' }; // Default Value       varobj =$.extend (Defaultval, Options);
return This. each (function () { varSelobject = $ ( This);//gets the current objectvarOldText = Selobject.text ();//gets the text value of the current objectvarOldbgcolor = Selobject.css ("Background-color");//gets the background color of the current objectvarOldcolor = selobject.css ("color");//gets the color of the current object's fontSelobject.hover (
function() {//defines a hover method. Selobject.text (obj. Text);//to assign a valueSelobject.css ("Background-color", obj. BackColor);//to assign a valueSELOBJECT.CSS ("Color", obj.) ForeColor);//to assign a value    },function() {selobject.text (OldText); Selobject.css ("Background-color", Oldbgcolor); Selobject.css ("Color", Oldcolor); }); }); }}) (JQuery);

The code is simple, there are some explanations on it, and it is not wordy at the moment.
How to use it? Very simple.
HTML Code:

<div id= "Div1" class= "Textbar" ></div> <div id= "Div2" class= "Textbar" >

JS Code:

$ (document). Ready (function  () {$ (' #div1' I am going  ' yellow' Red ' }); $ (' #div2 '). Texthover ({Text: ' I am Second div ... ')

You can see the effect.
I hope it will be of help to you.
OK, so far, it should be a basic element of plug-in development.

Originally there is a more complex code, sent together, wait for the next section!

Turn from: Broken Lolo

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.