JQuery plugin Development (advanced) and jquery Development (advanced)

Source: Internet
Author: User
Tags beautifier

JQuery plugin Development (advanced) and jquery Development (advanced)
JQuery plug-in Development Mode

In the software development process, a certain design pattern is required to guide the development. With the pattern, we can better organize our code, we also learned a lot of good practices from the models summarized by our predecessors.

According to the description of jQuery advanced programming, there are three main jQuery plug-in development methods:

  • Use $. extend () to extend jQuery

  • Add a new method to jQuery through $. fn

  • Use $. widget () to apply jQuery UI's component factory method to create

We usually use the second method for Simple plug-in development, which is relative to the third method. The third method is used to develop more advanced jQuery components. The components developed in this mode have many built-in jQuery features, such as the automatic saving of the status information of the plug-in, A variety of frequently used plug-ins are very considerate. I will not elaborate on them here.

The first method is too simple. It only adds a static method to the jQuery namespace or understood as jQuery. So we call $. the extend () function is directly called using the $ symbol ($. myfunction () without selecting the DOM element ($ ('# example '). myfunction ()). See the following example.

$. Extend ({sayHello: function (name) {console. log ('hello, '+ (name? Name: 'dude') + '! ') ;}}) $. SayHello (); // call $. sayHello ('wayou'); // call with Parameters

Running result:

In the code above, a sayHello function is added to jQuery through $. extend () and then called directly through $. Now you can think that we have completed a simple jQuery plug-in.

As you can see, this method is convenient to define some auxiliary methods. For example, a custom console outputs information in a specific format. Once defined, jQuery can call it wherever necessary in the program.

$. Extend ({log: function (message) {var now = new Date (), y = now. getFullYear (), m = now. getMonth () + 1 ,//! In JavaScript, the monthly value starts from 0. d = now. getDate (), h = now. getHours (), min = now. getMinutes (), s = now. getSeconds (), time = y + '/' + m + '/' + d + ''+ h + ':' + min + ':' + s; console. log (time + 'my App: '+ message) ;}}) $. log ('initializing... '); // call

However, this method cannot take advantage of jQuery's powerful selector. To process DOM elements and apply the plug-in to the selected elements, you still need to use the second development method. Most of the plug-ins you see or use are developed in this way.

Plug-in development

Next we will look at the second method of jQuery plug-in development.

Basic Method

Let's take a look at its basic format:

$.fn.pluginName = function() {    //your code goes here}

Basically, you can add a method to $. fn. The name is our plug-in name. Then our plug-in code is expanded in this method.

For example, if we convert the color of all links on the page to red, we can write this plug-in as follows:

$. Fn. myPlugin = function () {// here, this refers to the element selected by jQuery // example: $ ('A '), then this = $ ('A') this.css ('color', 'red ');}

Within the function defined by the plug-in name, this refers to the elements selected by the jQuery selector when we call the plug-in. this is generally a set of jQuery types. For example, $ ('A') returns the set of all a tags on the page, and the set is already of the jQuery packaging type, that is, when you operate on it, you can directly call other jQuery methods without using the dollar symbol to wrap it.

Therefore, in the above plug-in code, we call jQuery's css () method on this, which is equivalent to calling 'a'{.css ().

It is important to understand the meaning of this in this place. In this way, you can understand why the jQuery method can be commercially used. In other places, this is called only when jQuery is repackaged. Beginners are easily confused by the value of this, but it is not difficult to understand it.

Now we can go to the page and try our code. put several links on the page. after calling the plug-in, the link font turns red.

<Ul> <li> <a href = "http://www.webo.com/liuwayong"> my weibo </a> </li> <a href = "http: // http://www.cnblogs.com/Wayou/ "> my blog </a> </li> <a href =" http://wayouliu.duapp.com/"> my site </a> </li> </ /ul> <p> This is a p tag, not a tag, 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>

Running result:

Next, we will process each specific element in the plug-in code, instead of processing a set, so that we can perform corresponding operations on each element.

We already know that this refers to the set returned by the jQuery selector. the each () method can process every element in the collection, but note that inside the each method, this refers to a common DOM element, if you need to call the jQuery method, you need to use $ to rewrap it.

For example, to display the real address of the link in each link, first traverse all the tags through each, then obtain the value of the href attribute and add it to the link text.

After the change, our plug-in code is:

$. Fn. myPlugin = function () {// here, this refers to this.css ('color', 'red') selected by jQuery; this. each (function () {// operate each element $ (this ). append (''+ $ (this ). attr ('href '));}))}

The call code is the same. We can call this plug-in by selecting all the labels on the page.

Running result:

Now, you can write jQuery plug-ins with simple functions. Is it not that difficult.

The following describes the receipt of parameters in the compilation of jQuery plug-ins.

Support chain call

We all know that jQuery supports chained calling. After DOM elements are selected, other methods can be called continuously.

To prevent the plug-in from breaking this type of chained call, you only need to return it.

$. Fn. myPlugin = function () {// here, this indicates this.css ('color', 'red') selected by jQuery; return this. each (function () {// operate each element $ (this ). append (''+ $ (this ). attr ('href '));}))}
Let the plug-in receive Parameters

A powerful plug-in can be customized by users at will, which requires us to provide comprehensive considerations when writing the plug-in and provide appropriate parameters as much as possible.

For example, if we do not want to make the link red, we allow the plug-in user to define the color of the display. To do this, you only need to input a parameter when calling the plug-in. At the same time, we receive the code in the plug-in. On the other hand, in order to be flexible, users can not pass the parameter, the plug-in will give the default value of the parameter.

Generally, the extend method of jQuery is used to receive the parameters of the processing plug-in. As mentioned above, but when the extend method is passed to a single object, this object will be merged into jQuery, so we can call the methods contained in the new merged object on jQuery, as shown in the above example. When more than one parameter is passed to the extend method, it merges all parameter objects into the first one. At the same time, if an object has an attribute with the same name, the preceding attributes will be overwritten when merged.

With this, we can define an object in the plug-in that saves the default values of the plug-in parameters, and merge the received parameter objects into the default objects, finally, the user-specified parameter uses the specified value. unspecified parameters use the default value of the plug-in.

For ease of demonstration, specify another parameter fontSize, which allows you to set the font size when calling the plug-in.

$.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, when we call this function, we specify the color. If the font size is not specified, the default value of 12px in the plug-in will be used.

$('a').myPlugin({    'color': '#2C9929'});

Running result:

Specify the color and font size at the same time:

$('a').myPlugin({    'color': '#2C9929',    'fontSize': '20px'});

Protect default parameters

Note that the above Code will change the value of ults when calling extend. This is not good because it is used as a plug-in because some of the items should be unchanged, in addition, if you want to use these default values in the subsequent code, When you access it again, the parameter has been changed by the user.

A good practice is to use a new null object as $. the first parameter of extend, defaults and the parameter object passed by the user follow closely. The advantage of doing so is that all values are merged into this empty object, protecting the default values in 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 parameter return this.css ({'color': settings. color, 'fontsize': settings. fontSize });}

After receiving and processing parameters, the plug-in can compile a more robust and flexible plug-in. If you want to write a complex plug-in, the amount of code will be very large, and how to organize the code becomes a problem to be faced. Without a good way to organize the code, the overall feeling will be messy, at the same time, it is not easy to maintain. Therefore, packaging all the method attributes of the plug-in to an object and developing it with object-oriented thinking will undoubtedly make the work much easier.

Object-oriented plug-in development
// Define the Beautifier constructor var Beautifier = function (ele, opt) {this. $ element = ele, this. ults = {'color': 'red', 'fontsize': '12px ', 'textrecoration': 'none'}, this. options = $. extend ({}, this. defaults, opt)} // defines the Beautifier method. prototype = {beauent: function () {return this.w.element.css ({'color': this. options. color, 'fontsize': this. options. fontSize, 'textrecoration': this. options. textDecoration}) ;}}// use the Beautifier object in the plug-in $. fn. myPlugin = function (options) {// create the Beautifier object var beautifier = new Beautifier (this, options); // call its method return beautifier. beautify ();}

Call method:

$(function() {    $('a').myPlugin({        'color': '#2C9929',        'fontSize': '20px'    });})

Specify the underlined text (the new feature in the Beautifier object is not underlined by default, as shown in the preceding example:

$(function() {    $('a').myPlugin({        'color': '#2C9929',        'fontSize': '20px',        'textDecoration': 'underline'    });})
About namespaces

Wrap your code with self-called anonymous Functions

(Function () {// defines the Beautifier constructor var Beautifier = function (ele, opt) {this. $ element = ele, this. ults = {'color': 'red', 'fontsize': '12px ', 'textrecoration': 'none'}, this. options = $. extend ({}, this. defaults, opt)} // defines the Beautifier method. prototype = {beauent: function () {return this.w.element.css ({'color': this. options. color, 'fontsize': this. options. fontSize, 'textrecoration': this. options. textDecoration}) ;}}// use the Beautifier object in the plug-in $. fn. myPlugin = function (options) {// create the Beautifier object var beautifier = new Beautifier (this, options); // call its method return beautifier. beautify ();}})();

Pass System variables to the plug-in as variables

; (Function ($, window, document, undefined) {// our code .. // Blah...}) (jQuery, window, document );

As for this undefined, it is a little interesting. In order to get undefined that has not been modified, we did not pass this parameter, but received it when receiving it because it was not actually passed, so the location 'undefined' receives the actual 'undefined. Is it a bit of a hack that deserves a detailed understanding? Of course I did not invent it, but I learned from my previous experiences.

So our plug-in is like this:

; (Function ($, window, document, undefined) {// defines the Beautifier constructor var Beautifier = function (ele, opt) {this. $ element = ele, this. ults = {'color': 'red', 'fontsize': '12px ', 'textrecoration': 'none'}, this. options = $. extend ({}, this. defaults, opt)} // defines the Beautifier method. prototype = {beauent: function () {return this.w.element.css ({'color': this. options. color, 'fontsize': this. options. fontSize, 'textrecoration': this. options. textDecoration}) ;}}// use the Beautifier object in the plug-in $. fn. myPlugin = function (options) {// create the Beautifier object var beautifier = new Beautifier (this, options); // call its method return beautifier. beautify () ;}}) (jQuery, window, document );

A secure, well-structured, and well-organized plug-in has been compiled.

Refer:
JQuery official site Learning Center on plug-in development of the article: http://learn.jquery.com/plugins/
JQuery official site plug-in center: http://plugins.jquery.com/
JQuery official website plug-in release guide: http://plugins.jquery.com/docs/publish/
Address: http://www.cnblogs.com/Wayou/p/jquery_plugin_tutorial.html

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.