Getting Started with jquery plugins

Source: Internet
Author: User

I: Introduction

Some Web developers will refer to a jquery class library and then write a write ("#") on the Web page ("#"), ("."), and write for a couple of years to say they are very familiar with jquery. I used to be such a person, until there was a technical exchange in the company, I changed my opinion of myself.

Second: universal knowledge of jquery

Knowledge 1: When writing plugins with jquery, the core approach is as follows two:

    • $.extend (object) can be understood to add a static method to jquery.

    • $.fn.extend (object) can be understood as adding a method to a jquery instance.

Basic definition and invocation:

//$.extend definition and invocation$.extend ({fun1:function() {alert ("Execution method One"); }}); $.fun1 ();//$.fn.extend definition and invocation$.fn.extend ({fun2:function() {alert ("Execution Method 2"); }});$( This). fun2 ();//equivalent to$.FN.FUN3 =function() {alert ("Execution method Three"); }$( This). FUN3 ();

Knowledge 2:jquery (function () {}); differs from (function ($) {}) (JQuery):

JQuery (function  () {}); // equivalent to $ (document). Ready (function  () {});(function  ($) {}) (jQuery); // equivalent var function ($) {};FN (jQuery);

jQuery(function () { });Is the code in the execution method after a DOM element has been loaded.

(function ($) { })(jQuery); An anonymous function is defined, where jquery represents the argument for this anonymous function. Often used in jquery plug-in development, the role of defining the plug-in's private domain.

Three: The development of jquery plug-in standard structure

1, define the scope: Define a jquery plug-in, the first to put the plug-in code in a place that is not disturbed by the outside world. If you are professional, you need to define a private scope for this plugin. External code cannot directly access the code inside the plug-in. The code inside the plugin does not pollute global variables. The dependence of plug-in and running environment is decoupled in a certain role. Having said so much, how do you define a private scope for a plug-in?

// Step01 Defining the scope of jquery (function  ($) {}) (jQuery);

Don't underestimate this scope, just as important as C # defines a class keyword.

2. Expand a plugin for jquery: When you have defined the scope of jquery, the most important and most urgent step is to add an extension method to this jquery instance. First we name a method for this Jqury plugin, called Easyslider, when we call this plugin, we can pass some parameters to the plugin through the options. The specific definition method looks like the following code:

// Step01 Defining the scope of jquery (function  ($) {    ///STEP02 Plug-in extension method name    function  (options) {            }}) (jQuery);

So far, one of the simplest jquery plugins has been completed. When called, you can

    • $("#domName").easySlider({})

    • $(".domName").easySlider({})

    • More ways to call this plugin.

3. Set default value: Define a jquery plug-in, just like defining a. NET control. A perfect plugin should be a more flexible attribute. Let's take a look at this piece of code:

<asp:textbox id= "TextBox1" width= "height=", "runat=" and "Server" ></asp:TextBox>

The TextBox control has a width and height property that allows the user to freely set the height and width of the control when using a TextBox, or not to set a value because the control itself has a default value. When you are ready to develop a jquery plugin, there should be a default value when the user does not specify a property, and in jquery you can implement such a definition in two steps, as shown in the following code step03-a,step03-b.

//Step01 Defining the scope of jquery(function ($) {    //default Value properties for Step03-a plugins    varDefaults ={previd:' Prevbtn ', Prevtext:' Previous ', NextID:' Nextbtn ', Nexttext:' Next '//...    }; //extension method name for STEP02 plug-in$.fn.easyslider =function(options) {//step03-b Merge User custom properties, default properties        varOptions =$.extend (defaults, options); }}) (JQuery);

The people who do the procedure like to innovate, change the variable name, change a line ah these. When you see the use of var defaults = {} a default property, when you write the jquery plugin to think differently, so use var default01 ={} , var default02 ={} to represent the default properties. Then the default attribute names are varied and getting worse. It is recommended that when you write a jquery plugin, the default properties are defined by using the defaults variable to represent the default property, which makes the code more readable.

Someone saw this line of code: var options = $.extend(defaults, options) and frowned, expressing puzzled. Let's start by looking at the following code:

varOBJ01 ={name:"English name: Sam Xiao", Age:29, Girlfriend: {name:"Yang", Age:29    } }varOBJ02 ={name:"Chinese name: Xiaojian", Girlfriend: {name:"YY"    } };varA =$.extend (obj01, obj02);varb = $.extend (true, obj01, obj02);varc =$.extend ({}, obj01, obj02);varD = $.extend (true, {}, obj01, obj02);

Copy the code into the development environment and look at the value of the a,b,c,d to see what it var options = $.extend(defaults, options) means. Represents the options to overwrite the value of the defaults and assigns the value to the options.
In a plug-in environment, the value that represents the user setting overrides the default value of the plug-in, or the default value of the plug-in if the user does not have a property that sets the default value.

4, support jquery selector: jquery selector, is a good feature of jquery, if our plug-in writing does not support jquery selector, is indeed a great pity. In order to enable your jquery plugin to support multiple selectors, our code should be defined like this:

//Step01 Defining the scope of jquery(function ($) {    //default Value properties for Step03-a plugins    varDefaults ={previd:' Prevbtn ', Prevtext:' Previous ', NextID:' Nextbtn ', Nexttext:' Next '//...    }; //extension method name for STEP02 plug-in$.fn.easyslider =function(options) {//step03-b Merge User custom properties, default properties        varOptions =$.extend (defaults, options); //step4 support for jquery selectors         This. each (function () {        }); }}) (JQuery);

5, Support jquery link call: The above code looks perfect, in fact, it is not so perfect. Link calls are not supported so far. In order to achieve the effect of a link call, you must return each element of the loop

//Step01 Defining the scope of jquery(function ($) {    //default Value properties for Step03-a plugins    varDefaults ={previd:' Prevbtn ', Prevtext:' Previous ', NextID:' Nextbtn ', Nexttext:' Next '//...    }; //extension method name for STEP02 plug-in$.fn.easyslider =function(options) {//step03-b Merge User custom properties, default properties        varOptions =$.extend (defaults, options); //step4 support for jquery selectors        //STEP5 supports chained calls        return  This. each (function () {        }); }}) (JQuery);

Such a definition can support link invocation. Such calls are supported: '

$ (". Div"). Easyslider ({        previd:"", Prevtext: "    })    . css ({           " border-width ":" 1 " ,        " Border-color ":" Red ",           " Border-bottom-style ":" Dotted " });

6, Plug-in methods: often implement a plug-in function requires a lot of code, it is possible to hundreds of lines, thousands of lines, even tens of thousands of lines. We structure this code and we have to use function. In the 1th has been said, in the plug-in definition of the method, the outside world can not directly call, I defined in the plug-in method also does not pollute the external environment. Now try to define some methods in the plugin:

//Step01 Defining the scope of jquery(function ($) {    //default Value properties for Step03-a plugins    varDefaults ={previd:' Prevbtn ', Prevtext:' Previous ', NextID:' Nextbtn ', Nexttext:' Next '//...    }; //step06-a defining methods in plugins    varShowLink =function(obj) {$ (obj). Append (function() {return"(" + $ (obj). attr ("href") + ")" }); }    //extension method name for STEP02 plug-in$.fn.easyslider =function(options) {//step03-b Merge User custom properties, default properties        varOptions =$.extend (defaults, options); //step4 support for jquery selectors        //STEP5 supports chained calls        return  This. each (function () {            //Step06-b defining methods in pluginsShowLink ( This);    }); }}) (JQuery);

Step step06-a: Define a method called Showlink () in the plugin; This method can not be called directly outside the plugin, a bit like a private method in C # class, can only meet the internal use of plug-ins. Step Step06-b demonstrates how to invoke the inside of a plug-in method.

Getting Started with jquery plugins

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.