JQuery plugin development is actually very simple

Source: Internet
Author: User
Tags bind eval exception handling extend min xmlns

Some people often ask some tips, so simply write an article for the jquery enthusiasts, is a welcome.
Infrastructure
a) style
Many people will think that style is a very complex thing, need a cool mind with extraordinary aesthetics to design a pleasing UI, put aside the picture design does not say, in fact, CSS is a few attributes: Position,margin,padding,width,height, Left,top,float,border,background ...

The beauty of UI design depends to a great extent on the designer's understanding of color matching and the coordination of the overall effect. To give a simple example, a simple page, sloppy people:

Copy the code code as follows:
<title>test page</title>
<body>
jquery is a framework. After compression there are more than 30 K bar.
</body>


The attentive person:

Copy the code code as follows:
<title>test page</title>
<style type= "Text/css" >
Body
{
font-family: ' Song body ';
font-size:12px;
}
</style>
<body>
jquery is a framework. After compression there are more than 30 K bar.
</body>

The person who concentrates:

[Ctrl + A full selection Note: If you need to introduce external JS need to refresh to execute]
Let's compare the UI effects of the three:



At a glance, perhaps a lot of sites lose attention precisely because of this humble font-family,font-size. Of course, this is just a simple example, master CSS should start from a simple, basic, in practice and continue to deepen.
b) Script
We also need to have a deep understanding of JavaScript, for Dom, XHR, Regex, call-apply, prototype and so on should have a certain understanding.

Some people will say to what use Ah, the operation of the DOM in fact through the getElementById, getElementsByTagName and other APIs can be easily completed, this is true, when the idea is determined, thought is the focus, A piece of code is the essence or dross is easy to distinguish, the reason or depends on yourself, to give a simple example, a lot of HTML assembly, passers-by:

Copy the code code 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> ';
}


Passerby B:

Copy the code code as follows:
String.prototype.format = function () {
var args = arguments;
Return This.replace (/{(\d{1})}/g, function () {
return args[arguments[1]];
});
};
var a = new Array (1,2,3,4,5,6,7,8,9,0);
var m = ' <li class= ' style_{0} ' >{0}</li> ';
for (var i = 0; i < a.length; i++) {
Menu + = M.format (A[i]);
}

Elegant and efficient code is clearly more appealing in a way that is clearly implemented.
"Practice"
jquery is developed or used, and more inspiration comes from practice, not copy| | Paste (the student who pursues take doctrine can leave).
So here I will use a simple example to explain the jquery plug-in development process, can extrapolate see you see Officer.

"Purpose"

Before developing a plug-in we need to have a clear understanding of their own purpose, there is a clear sense of direction, then this time I as a sample plug-in to render a slider-slider for the UI, perennial engaged in or temporarily focused on the development of Win32 students should be more understanding.

Sketch


We also need a sketch to describe the "looks" of our plug-in (event-driven or API-encapsulated can be ignored) before actually coding.
Many students in the UI development is often busy to collect a variety of small pictures (not proficient PS or iconworkshop people), in fact, beautiful icons can actually beautify our UI, but my general approach is to write easy to extend the CSS, pre-UI rendering as little use of pictures, more lines to complete.
OK, the word to the positive roll, then my slider design sketch is:


Explain the following several words to be used:
Slider: This section is used as a drag-and-drop handle that allows the user to update the position of the completed bar by dragging this section.
Completed: This section acts as an inline element of bar, as a special effect to show the distance between the slider and the starting point, which is associated with the slider's value.
The Bar:slider carrier, the full value of the completed.

Ideas:
Slider as a handle to provide drag and drop function, the action area is bar, the completed bar must be updated in real-time (length), affecting the area of the slider to the left side of the bar distance.

"Encode"

The development of jquery Ui/effect plug-ins In many cases need to interact with the UI, so in the rendering need to provide HTML tree to draw our plug-in, and finally through the JS Dom to output, then in the simple DOM structure of the drawing I will directly use JS to complete, However, if the nesting is more complex, we should first use HTML to complete, and then into the JS output.

HTML tree:

Copy the code code as follows:
<div class= "Defaultbar" >
<div class= "jquery-completed" > </div>
<div class= "Jquery-jslider" > </div>
</div>
Deafultbar Bar
Jquery-completed-Completed
Slider Jquery-jslider

Pre-UI rendering we do not use pictures, as far as possible with lines, colors to complete:
Css
Copy the code code 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 property of bar to relative to facilitate the floating of child nodes (child nodes use Position:absolute to get inline floating effects).
So we can look at the UI effect that this CSS and HTML tree produces:

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

When we draw the UI, we can formally write the jquery plugin code, but before we do, we need to have some understanding of some of the norms of jquery plug-in development.
1. Use closures:

Copy the code code as follows:
(function ($) {
Code goes here
}) (JQuery);

This is from the official jquery plug-in development specification requirements, the use of this method of writing what is the benefit of it.

A) avoid global dependencies.

b) Avoid third-party damage.
c) compatible with jquery operator ' $ ' and ' jquery '

We know that this code will be parsed with the following code:

Copy the code code as follows:
var JQ = function ($) {
Code goes here
};
JQ (JQuery);

This effect is at a glance.

2. Expansion
jquery provides 2 ' base classes '-$.extend and $.fn.extend for user extensions.

$.extend is used to extend its own methods, such as $.ajax, $.getjson, and so on, $.fn.extend is used to extend the jquery class, including methods and operations on jquery objects. To maintain the integrity of jquery, I tend to use $.fn.extend for plug-in development with minimal use of $.extend.
3. Selector
jquery provides a powerful and compatible selection of CSS versions, but finds that many students do not focus on efficiency when using selectors.
A) using the ID selector as much as possible, the jquery selector uses an API based on getElementById or getelementsbytagname, so you know that the most efficient is the ID selector, Because jquery calls getElementById directly to fetch the DOM, and the style selector gets the jquery object, it often uses getelementsbytagname to get and then filter.
b) The style selector should specify tagname as much as possible, and if the developer uses the style selector to get the DOM, and the DOM is of the same type, such as getting all the div classname as jquery, then we should use the notation $ (' div.jquery ') Rather than $ ('. jquery '), the benefits of writing this are obvious, and when you get the DOM jquery gets the div and then filters it instead of getting all the DOM re-filters.
c) Avoid iterations, and many students prefer to use an iterative approach when using jquery to get the DOM in the specified context, such as $ ('. jquery. Child '), to get all the classname nodes that are classname under the DOM of jquery, In fact, the cost of writing code is very large, jquery will continue to carry out deep traversal to get the necessary elements, even if it is really necessary, we should also use such as $ (Selector,context), $ (' Selector1>selector2 '), $ ( Selector1). Children (Selector2), $ (Selctor1). Find (Selector2) way.

Start Coding

The topic is a bit far, OK, after a clear understanding of the UI we can use JS to output HTML.
We use JSlider to name this slider plugin (in order to avoid plugin conflicts, plug-in naming should also be very elegant, here I am vulgar).
Copy the code code as follows:
$.extend ($.fn, {
<summary>
Apply a slider UI
</summary>
Jslider:function (setting) {
}
});

In plug-in development, the standard way is to separate the metadata and open the API, such as the setting parameter here in the value, and sometimes in order to reduce the amount of code written, I am accustomed to directly within the plug-in assignment:

Copy the code code 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);

The normative approach:

Copy the code code 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, here is a description of what I have defined as the effects of these APIs:
Renderto:jslider carrier, container, can be a jquery object, can also be a selector.
Enable:jslider plug-in is available, true when end-user can be dragged, otherwise prohibited.
The initial value of the Initposition:jslider, ' Max ' or ' min ', which is the value of the slider, 1 or 0.
The length of the Size:jslider parameter, including the length of the 2 value Barwidth-bar, Sliderwidth-slider.
The style name of the Barcssname:bar, which makes it easy for end-user to extend its style.
The style name of the completedcssname:completed.
The style name of the Slidercssname:slider.
Sliderhover:slider the style name when focusing.
Onchanging:slider the event that is triggered when dragged.
Onchanged:slider the event that is triggered at the end of the drag.

At this point we need to cast the Renderto into a jquery object (compatible with the case of using selector):

Ps.renderto = (typeof Ps.renderto = = ' string '?)
$ (Ps.renderto): Ps.renderto);
Then output the HTML tree to render:

/*---------->
HTML tree:
Copy the code code as follows:
<div>---->sliderbar
<div> </div>----> Completed bar
<div> </div>----> Sliders
</div>
<-----------* *
var Sliderbar = $ (' <div><div> </div><div> </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);

This allows us to render HTML directly on the UI and render it with custom CSS, using Sliderbar, Completedbar, slider to cache the three objects we need.

OK, after rendering the UI we need to provide a way to implement slider drag, before we need to implement a method, that is, Completedbar real-time update, that is, when dragging the slider to let Completedbar always fill the left area:

Copy the code code as follows:
var bw = Sliderbar.width (), SW = Slider.width ();
Make sure the slider is displayed in the bar (make a limited)
ps.limited = {min:0, MAX:BW-SW};
if (typeof window. $sliderProcess = = ' undefined ') {
window. $sliderProcess = new Function (' obj1 ', ' obj2 ', ' left ',
' Obj1.css (\ ' Left\ ', left); Obj2.css (\ ' width\ ', left);
}
$sliderProcess (Slider, Completedbar, eval (' ps.limited. ' + ps.initposition));

The BW,SW is used to store the length of the Sliderbar and sliders, where the value in Ps.size is not directly used to prevent the border-width in the style from damaging the width.

Define a private member limited to store the maximum and minimum values of slider[left] and use the eval (' ps.limited. ' + ps.initposition) directly later to avoid the switch operation.
It is also necessary to define a global function to locate the padding length of the Completedbar and the left distance of the slider, which I named $sliderprocess.
Then the rest of our work is the slider drag function, then here I will use a previously released jquery drag plugin, and do the appropriate amount of custom:

Copy the code code 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 Parameters:1st:percentage, 2nd:event
Ps.onchanging (L/ps.limited.max, E);
},
Drop:function (e) {
Slider.removeclass (Ps.sliderhover);
Push 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);
});
}

This way, when the JSlider enable property is True, the MouseMove event is bound when end-user is pressed, and when the mouse bounces, we only need to update the left property of the slider and the width of the completedbar synchronously. While binding the Onchanging method in the drag, bind the OnChanged method in the drop, the parameters that are pushed to the two methods are the same,1> percentage, which is the value of value, between 0~1,2>event.

So far our JSlider plug-in is basically shaped to provide users with a slider that can be dragged.

"Extended"
Sometimes the user is not so easy to meet, so someone shouted: "I want to set the value myself, why not provide this function." ”。

Then we need to expose a method for the user to set the value of the JSlider, the first consideration is that as a method requires a function object (jslider), then I do not want to pass the object as a parameter, then we still use this method as a plug-in to develop, We name the method Setslidervalue, open 2 parameters, V (value value) and callback (set the completed callback function).

namely: $.fn.setslidervalue (V,callback);
OK, then the rest is the role of the object, by the previous design, the slider when the main action on the 2 objects, sliders and Completedbar, then we add a piece of code at the end of the JSlider plug-in to return the slider object:

Copy the code code as follows:
Slider.data = {bar:sliderbar, completed:completedbar};
return slider;

This allows us to initialize the JSlider with a variable to get the JSlider object, and then call the Setslidervalue method, pseudo code:

Copy the code code 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, which 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);
}

This also calls the global function $sliderProcess to update completedbar[width] and Slider[left] When setting the value of the slider. Because of exception handling here, end-user can remove this exception-handling code when it is ensured that Setslidervalue is acting on the JSlider object.
Skin
According to JSlider API we can more easily set the skin for it, in order to make jslider more professional, we need 2 pictures:

Used as a ' bar ' for the completedbar background and a ' slider ' for the slider background, OK, we update the following style:

Blueskin
Copy the code code 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;
}

Since I still have the child node style using the default values for the API when I set the style, we just need to set the barcssname when we create the JSlider:

Copy the code code as follows:
var blue = $.fn.jslider ({
Renderto: ' #slidercontainer ',
Size: {barwidth:500, sliderwidth:10},
Barcssname: ' Bluebar ',
Onchanging:function (percentage, E) {
Code goes here
}
});

The rendered UI:


Let's set its value this way:

Copy the code code as follows:
Set percentage with a callback function
Blue.setslidervalue (0.65, function (percentage) {
Code goes here
});

"Versatility"
Of course, not only can we use JSlider as a slider, but sometimes it is also a ProgressBar:

(The code I will not post, directly in the demo to view;-))
Summary
This concludes with a simple introduction to the development process of a jquery plugin and the details that should be noted in the development, so in the next article I'll show you how to create a general-purpose AutoComplete plugin.

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.