JQuery plug-in development is actually very simple

Source: Internet
Author: User

Some people often ask for some tips, so simply write such an article for jQuery fans.
[Basics]
A) style
Many people will think that style is a very complicated thing. They need a calm mind and an extraordinary aesthetic to design a pleasing UI. Aside from image design, css is actually just a few attributes: position, margin, padding, width, height, left, top, float, border, background...

The beauty of the UI design depends largely on the designer's grasp of the color scheme and coordination of the overall effect. For example, a simple page, sloppy person:

Copy codeThe Code is as follows:
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> Test Page </title>
</Head>
<Body>
JQuery is a framework! After compression, there will be more than 30 k.
</Body>
</Html>


Careful person:

Copy codeThe Code is as follows:
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> Test Page </title>
<Style type = "text/css">
Body
{
Font-family: ' ';
Font-size: 12px;
}
</Style>
</Head>
<Body>
JQuery is a framework! After compression, there will be more than 30 k.
</Body>
</Html>

Attentive person:

<Html xmlns = "http://www.w3.org/1999/xhtml"> <pead> <title> Test Page </title> <style type = "text/css"> body {font-family: 'verdana ', 'body'; font-size: 12px ;}</style> </pead> <body> jQuery is a framework! After compression, there will be more than 30 k. </Body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
We will compare the UI effects of the three items:



At a glance, many websites may lose their attention because of the inconspicuous font-family and font-size. Of course, this is just a simple example. To master css, you should start with simplicity, start with basics, use it in practice, and continue to deepen.
B) script
We also need to have a deep understanding of javascript, and understand dom, xhr, Regex, call-apply, prototype, and so on.

Some people may say what they want to do. dom operations can be easily completed through getElementById, getElementsByTagName, and other APIs. This is correct. After the idea is determined, the idea is the focus. It is easy to tell whether a piece of code is the essence or the dregs. The reason is that it depends on yourself. For a simple example, a lot of html assembly, passers-by:

Copy codeThe Code is as follows:
Var a = new Array (10 );
Var menu = '';
For (var I = 0; I <a. length; I ++ ){
Menu + = '<li class = "style _' + a [I] + '">' + a [I] + '</li> ';
}


Passers-by B:

Copy codeThe Code is as follows:
String. prototype. format = function (){
Var args = arguments;
Return this. replace (/{(\ d {1})}/g, function (){
Return args [arguments [1];
});
};
Var a = new Array );
Var m = '<li class = "style _ {0}"> {0} </li> ';
For (var I = 0; I <a. length; I ++ ){
Menu + = m. format (a [I]);
}

With clear implementation methods, elegant and efficient code is obviously more attractive.
[Practice]
JQuery is developed or used. More inspiration is from practice, rather than copy. | paste (if you are pursuing the "tailism", you can leave ).
Here, I will use a simple example to describe the jQuery plug-in development process. If you can draw a line between them, let's look at them.

[Objective]

Before developing a plug-in, we need to have a clear understanding of our own purposes and a clear sense of direction. So this time, I will serve as an example plug-in, it is to present a Slider-slide for UI. Students who have been engaged in or temporarily focused on win32 development for years should be familiar with it.

Sketch
 

Before coding, we need a sketch to describe the "looks" of our plug-in (event-driven or API encapsulation can be ignored ).
Many people often collect various small pictures (not proficient in ps or iconworkshop) before developing the UI. In fact, beautiful icons can indeed beautify our UI, however, my general approach is to write css that is easy to expand. In the early stage, I used as few images as possible for UI rendering and used multiple lines.
OK, so my slider design sketch is:


The following several words are explained:
Slider: This part is used as a drag-and-drop handle. You can drag this part to update the location of the completed bar.
Completed: This part is an embedded element of bar. It is used as a special effect to display the distance between the slider and the starting point, that is, it is associated with the value of the slider.
Bar: the carrier of the slider, the full value of completed.

Ideas:
Slider acts as the handle to provide the drag and drop function. The area of the action is bar. During the Drag and Drop Process, the completed bar must be updated (length) in real time, and the impact area is the distance from slider to the left end of bar.

[Encoding]

The development of jQuery UI/Effect plug-ins often requires interaction with the UI. Therefore, we need to provide an Html tree for rendering our plug-in and finally output it through the js dom, then, I will use js directly to plot a simple dom structure. However, if Nesting is complicated, we should first use html and then convert it into js output.

Html tree:

Copy codeThe Code is as follows:
<Div class = "defaultbar">
<Div class = "jquery-completed"> </div>
<Div class = "jquery-jslider"> </div>
</Div>
Deafultbar-> bar
Jquery-completed-> completed
Jquery-jslider-> slider

We do not use images for UI presentation in the early stage. We try to use lines and colors to complete the process:
Css
Copy codeThe Code is as follows:
/** // * ---- Default skin ----*/
. Defaultbar
{}{
Margin-top: 10px;
Height: 5px;
Background-color: # FFFFE0;
Border: 1px solid # A9C9E2;
Position: relative;
}
. Defaultbar. jquery-completed
{}{
Height: 3px;
Background-color: # 7d9edb;
Top: 1px;
Left: 1px;
Position: absolute;
}
. Defaultbar. jquery-jslider
{}{
Height: 15px;
Background-color: # E6E6FA;
Border: 1px solid # A5B6C8;
Top:-6px;
Display: block;
Cursor: pointer;
Position: absolute;
}

Set the position attribute of bar to relative to facilitate the floating of child nodes (the child node uses position: absolute to achieve the inline floating effect ).
Then we can see the UI effect produced by the css and html tree:

OK, with the required elements-slider, completed, bar.
Some specifications:

After the UI is drawn, we can officially compile the jQuery plug-in Code. However, before that, we still need to understand some of the normative aspects of jQuery plug-in development.
1. Use closure:

Copy codeThe Code is as follows:
(Function ($ ){
// Code goes here
}) (JQuery );

This is an official jQuery plug-in development standard requirement. What are the advantages of using this writing method?

A) avoid global dependency.

B) avoid third-party damages.
C) compatible with jQuery operators '$' and 'jQuery'

We know that this code will be the same as the following code when it is parsed:

Copy codeThe Code is as follows:
Var jq = function ($ ){
// Code goes here
};
Jq (jQuery );

The effect is clear at a glance.

2. Expansion
JQuery provides two 'base class'-$. extend and $. fn. extend.

$. Extend is used to extend its own methods, such as $. ajax and $. getJSON. $. fn. extend is used to extend jQuery classes, including methods and operations on jQuery objects. To maintain jQuery's integrity, I tend to use $. fn. extend for plug-in development and try to use $. extend as little as possible.
3. Selector
JQuery provides powerful functions and is compatible with various css version selectors. However, it is found that many users do not pay attention to efficiency when using selectors.
A) try to use the Id selector. The APIs used by jQuery's selector are based on getElementById or getElementsByTagName. Therefore, we can know that the most efficient Id selector is because jQuery will directly call getElementById to obtain the dom, getElementsByTagName is often used to obtain and filter jQuery objects through the style selector.
B) The style selector should specify the tagName as much as possible. If the developer uses the style selector to obtain the dom, And the dom belongs to the same type, for example, to obtain all div whose className is jquery, then we should use $ ('div. jquery ') instead of $ ('. jquery '). In this way, the write benefit is obvious. When getting the dom, jQuery will get the div and then filter it, instead of getting all the dom and then filter it.
C) Avoid iteration. Many users prefer to use the iteration method when using jQuery to obtain the dom in the specified context, such as $ ('. jquery. child '), get all the nodes whose className is child under the dom whose className is jquery. In fact, the cost for writing code is very large, jQuery will continuously perform deep traversal to obtain the required elements. Even if necessary, we should also use such elements as $ (selector, context), $ ('selector1> selector2 '), $(selector1 ). children (selector2), $(selctor1 ). find (selector2.

Start Encoding

The topic is a little too long. OK. After a clear understanding of the UI, we can use js to output html.
We use jSlider to name this slider plug-in (in order to avoid plug-in conflicts, the plug-in name should also be well-known. Here I will refer to it again ).
Copy codeThe Code is as follows:
$. Extend ($. fn ,{
/// <Summary>
/// Apply a slider UI
/// </Summary>
JSlider: function (setting ){
}
});

In plug-in development, the standard method is to separate the metadata and open the API. For example, the setting Parameter here is used to passing values. Sometimes, to reduce the amount of code written, I am used to assigning values directly in the plug-in:

Copy codeThe Code is as follows:
Var ps = $. extend ({
RenderTo: $ (document. body ),
Enable: true,
InitPosition: 'max ',
Size :{ barWidth: 200, sliderWidth: 5 },
BarCssName: 'defaultbar ',
CompletedCssName: 'jquery-completed ',
SliderCssName: 'jquery-jslider ',
SliderHover: 'jquery-jslider-hover ',
OnChanging: function (){},
OnChanged: function (){}
}, Setting );

Standard practice:

Copy codeThe Code is as follows:
$. Fn. jSlider. default = {
RenderTo: $ (document. body ),
Enable: true,
InitPosition: 'max ',
Size :{ barWidth: 200, sliderWidth: 5 },
BarCssName: 'defaultbar ',
CompletedCssName: 'jquery-completed ',
SliderCssName: 'jquery-jslider ',
SliderHover: 'jquery-jslider-hover ',
OnChanging: function (){},
OnChanged: function (){}
};
$. Extend ({}, $. fn. jSlider. default, setting );

OK. The following describes the functions of these Apis:
RenderTo: the carrier and container of jSlider. It can be a jQuery object or a selector.
Enable: whether the jSlider plug-in is available. If it is true, the end-user can be dragged. Otherwise, the end-user cannot be dragged.
InitPosition: Initial value of jSlider, 'max 'or 'Min', that is, the value of slider, 1 or 0.
Size: The jSlider parameter, including the length of two values, barWidth-bar, And sliderWidth-slider.
BarCssName: The style name of the bar, which allows the end-user to expand the style.
CompletedCssName: name of the completed style.
SliderCssName: The style name of the slider.
SliderHover: The style name when the slider is focused.
OnChanging: The event triggered when the slider is dragged.
OnChanged: The event triggered when the slider is dragged to the end.

In this case, we need to forcibly convert renderTo A jQuery object (compatible with selector ):

Ps. renderTo = (typeof ps. renderTo = 'string '?
$ (Ps. renderTo): ps. renderTo );
Then output the html tree to render:

/* ---------->
Html tree:
Copy codeThe Code is as follows:
<Div> ----> sliderbar
<Div> </div> ----> completed bar
<Div> </div> ----> slider
</Div>
<-----------*/
Var sliderbar =bar ('<div> </div> ')
. Attr ('class', ps. barCssName)
. Css ('width', ps. size. barWidth)
. AppendTo (ps. renderTo );
Var completedbar = sliderbar. find ('div: eq (0 )')
. Attr ('class', ps. completedCssName );
Var slider = sliderbar. find ('div: eq (1 )')
. Attr ('class', ps. sliderCssName)
. Css ('width', ps. size. sliderWidth );

In this way, Html is directly presented on the UI and rendered with custom css. sliderbar, completedbar, and slider are used to cache the three objects we need.

OK. After the UI is presented, we need to provide a method to implement slider drag. Before that, we need to implement a method, that is, the real-time update of completedbar, that is, when dragging the slider, let completedbar always fill the Left area:

Copy codeThe Code is as follows:
Var bw = sliderbar. width (), sw = slider. width ();
// Make sure that the slider was displayed in the bar (make a limited)
Ps. limited = {min: 0, max: bw-sw };
If (typeof window. $ sliderProcess = 'undefined '){
Window. $ sliderProcess = new Function ('obj1', 'obj1', 'left ',
'Obj1.css (\ 'left \ ', left1_1_obj2.css (\ 'width \', left );');
}
$ SliderProcess (slider, completedbar, eval ('ps. limited. '+ ps. initPosition ));

Bw and sw are used to store the length of sliderbar and slider. The value in ps. size is not directly used here to prevent the border-width in the style from damaging the width.

Defines a private member limited to store the maximum and minimum values of slider [left], and directly uses eval ('ps. limited. '+ ps. initPosition) to avoid switch operations.
At the same time, you also need to define a global Function to locate the length of the completedbar filling and the left distance of the slider. I name it $ sliderProcess.
The remaining work is the slider drag-and-drop function. Here I will use a jQuery drag-and-drop plug-in released earlier and make some customization:

Copy codeThe Code is as follows:
// Drag and drop
Var slide = {
Drag: function (e ){
Var d = e. data;
Var l = Math. min (Math. max (e. pageX-d. pageX + d. left, ps. limited. min), ps. limited. max );
$ SliderProcess (slider, completedbar, l );
// Push two parameters: 1st: percentage, 2nd: event
Ps. onChanging (l/ps. limited. max, e );
},
Drop: function (e ){
Slider. removeClass (ps. sliderHover );
// Push two parameters: 1st: percentage, 2nd: event
Ps.onChanged(parseInt(slider.css ('left')/sw-ps. limited. max, e );
$ (). Unbind ('mousemove ', slide. drag). unbind ('mouseup', slide. drop );
}
};
If (ps. enable ){
// Bind events
Slider. bind ('mousedown ', function (e ){
Var d = {
Left: parseInt(slider.css ('left ')),
PageX: e. pageX
};
$ (This). addClass (ps. sliderHover );
$ (). Bind ('mousemove ', d, slide. drag). bind ('mouseup', d, slide. drop );
});
}

In this way, when the jSlider enable attribute is true, bind the mousemove event when the end-user presses the mouse and remove the event when the mouse pops up. We only need to synchronously update the left attribute of the slider and the width of completedbar, at the same time, bind the onChanging Method to the drag and bind the onChanged Method to the drop method. The parameters pushed to the two methods are the same. 1> Percentage, that is, value, between 0 and 0 ~ 1, 2> event.

So far, our jSlider plug-in is basically formed, providing users with a slider that can be dragged.

[Expansion]
Sometimes the user is not so satisfied, so someone shouted, "I want to set the value myself. Why not provide this function ?".

In this case, we need to publish a method for the user to set the value of jSlider. The first consideration is to use the method to need a jSlider ), at this time, I don't want to pass in the target object as a parameter, so we still use this method as a plug-in for development. We name the method setSliderValue and open two parameters, v (value) and callback (the callback function after the setting is complete ).

That is, $. fn. setSliderValue (v, callback );
OK, so the rest is the target object. From the previous design, we can see that when slider is dragged, it mainly acts on two objects, slider and completedbar, then we add a piece of code at the end of the jSlider plug-in to return the slider object:

Copy codeThe Code is as follows:
Slider. data = {bar: sliderbar, completed: completedbar };
Return slider;

In this way, when initializing jSlider, we can directly use a variable to obtain the jSlider object, and then call the setSliderValue method. The pseudo code:

Copy codeThe Code is as follows:
Var slider = $. fn. jSlider ({});
Slider. setSliderValue (v, function (){});
SetSliderValue code:

Try {
// Validate
If (typeof v = 'undefined' | v <0 | v> 1 ){
Throw new Error ('\' v \ 'must be a Float variable between 0 and 1 .');
}
Var s = this;
// Validate
If (typeof s = 'undefined' |
Typeof s. data = 'undefined' |
Typeof s. data. bar = 'undefined '){
Throw new Error ('You bound the method to an object that is not a slider! ');
}
$ SliderProcess (s, s. data. completed, v * s. data. bar. width ());
If (typeof callback! = 'Undefined') {callback (v );}
}
Catch (e ){
Alert (e. message );
}

The global Function $ sliderProcess is also called to update completedbar [width] And slider [left] when setting the value of the slider. Because exception handling is performed here, if end-user can delete the Exception Handling Code when it ensures that setSliderValue is applied to the jSlider object.
Skin]
Based on the jSlider API, we can easily set the skin for it. To make jSlider more professional, we need two images:

The 'bar' used as the completedbar background and the 'slider' used as the slider background. OK. We will update the style:

BlueSkin
Copy codeThe Code is as follows:
/** // * ---- Blue skin ----*/
. Bluebar
{}{
Margin-top: 10px;
Height: 4px;
Background: # F7F7F7;
Border: solid 1px # 3e3e3e;
Position: relative;
}
. Bluebar. jquery-completed
{}{
Height: 4px;
Background: url (../images/slider/blue/bar.gif) left center no-repeat;
Top: 0;
Left: 0;
Position: absolute;
}
. Bluebar. jquery-jslider
{}{
Height: 17px;
Background: url (../images/slider/blue/slider.gif) center 0 no-repeat;
Top:-4px;
Display: block;
Cursor: pointer;
Position: absolute;
}
. Bluebar. jquery-jslider-hover
{}{
Background-position: center-17px;
}

Because I still allow the sub-node style to use the API default value when setting the style, we only need to set the barCssName when creating the jSlider:

Copy codeThe Code is as follows:
Var blue = $. fn. jSlider ({
RenderTo: '# slideriner iner ',
Size :{ barWidth: 500, sliderWidth: 10 },
BarCssName: 'bluebar ',
OnChanging: function (percentage, e ){
// Code goes here
}
});

Rendered UI:


Set the value as follows:

Copy codeThe Code is as follows:
// Set percentage with a callback function
Blue. setSliderValue (0.65, function (percentage ){
// Code goes here
});

[Versatility]
Of course, we can not only use jSlider as a slider, but sometimes it is also a progressbar:

(I will not post the code and view it directly in the demo ;-))
[Summary]
The entire article ends here. It briefly introduces the development process of a jQuery plug-in and the details that should be paid attention to during development, in the next article, I will introduce how to create a general Automatic completion plug-in.

Related Article

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.