Jquery extension plug-in method

Source: Internet
Author: User

From: http://www.iteye.com/topic/545971

There are two types of jquery plug-in development:

One is class-level plug-in development, that is, adding a new global function to jquery is equivalent to adding a method to the jquery class itself. Jquery's global functions belong to the jquery namespace, and the other is object-level plug-in development, that is, adding methods to jquery objects. The following describes the development of the two functions in detail.

1. Class-level plug-in development

The most direct understanding of class-level plug-in development is to add class methods to the jquery class, which can be understood as adding static methods. A typical example is the $. Ajax () function, which is defined in the namespace of jquery. The following extensions can be used for class-level plug-in development:

1.1 Add a new global function

To add a global function, we only need to define it as follows:

Java code

Jquery. Foo = function (){

Alert ('this is a test. This is only a test .');

};

  

1.2 add multiple global functions

Add multiple global functions, which can be defined as follows:

Java code

Jquery. Foo = function (){

Alert ('this is a test. This is only a test .');

};

The call time is the same as that of a function: jquery. Foo (); jquery. Bar (); or $. Foo (); $. Bar ('bar ');

1.3 Use jquery. Extend (object );

Java code

Jquery. Extend ({

Foo: function (){

Alert ('this is a test. This is only a test .');

},

Bar: function (PARAM ){

Alert ('this function takes a parameter, which is "'+ Param + '".');

}

});

1.4 Use a namespace

Although a large number of JavaScript function names and variable names are not allowed in the jquery namespace. But it is still inevitable that some functions or variables will conflict with other jquery plug-ins, so we are used to encapsulating some methods into another custom namespace.

Java code

Jquery. myplugin = {

Foo: function (){

Alert ('this is a test. This is only a test .');

},

Bar: function (PARAM ){

Alert ('this function takes a parameter, which is "'+ Param + '".');

}

};

The namespace function is still a global function. The method used for calling is as follows:

$. Myplugin. Foo ();

$. Myplugin. Bar ('baz ');

With this technique (using an independent plug-in name), we can avoid conflicts between functions in the namespace.

2. Object-level plug-in development

Object-level plug-in development requires the following two forms:

Form 1:

Java code

(Function ($ ){

$. FN. Extend ({

Pluginname: function (OPT, callback ){

// Our plugin implementation code goes here.

}

})

}) (Jquery );

 

Form 2:

Java code

(Function ($ ){

$. FN. pluginname = function (){

// Our plugin implementation code goes here.

};

}) (Jquery );

The above defines a jquery function with the form parameter $. After the function definition is complete, pass the jquery real parameter in. Call and execute now. The advantage is that when writing the jquery plug-in, we can also use the $ alias instead of causing conflicts with prototype.

 

2.1 declare a name in the jquery namespace

This is a single plug-in script. If your script contains multiple plug-ins or plug-ins that are mutually inverse (for example, $. FN. dosomething () and $. FN. undosomething (), you need to declare multiple function names. However, when writing a plug-in, we usually try to use only one name to include all its content. Our example plug-in is named "highlight"

Java code

$. FN. hilight = function (){

// Our plugin implementation code goes here.

};

Our plug-in is called like this:

$ ('# Mydiv'). hilight ();

But what if we need to break down our implementation code into multiple functions? There are many reasons: design needs; easier or easier to read implementation; and more in line with object-oriented. This is really a headache. It breaks down the function implementation into multiple functions without adding additional namespaces. To realize that and use functions are the most basic class objects in Javascript, we can do this. Like other objects, functions can be specified as attributes. Therefore, we have declared "hilight" as a jquery attribute object. Any other attribute or function that we need to expose can be declared in the "hilight" function. Continue later.

2.2Accept the options parameter to control the actions of the plug-in.

Let's add features for our plug-in to specify the foreground color and background color. We may make options pass to the plug-in function like an options object. For example:

Java code

// Plugin Definition

$. FN. hilight = function (options ){

VaR defaults = {

Foreground: 'red ',

Background: 'yellow'

};

// Extend our default options with those provided.

VaR opts = $. Extend (defaults, options );

// Our plugin implementation code goes here.

};

Our plug-in can be called as follows:

$ ('# Mydiv'). hilight ({

Foreground: 'blue'

});

2.3 default settings of the exposure plug-in

One improvement of the above Code is to expose the default settings of the plug-in. This makes it easier for plug-in users to overwrite and modify plug-ins with less code. Next we start to use function objects.

Java code

// Plugin Definition

$. FN. hilight = function (options ){

// Extend our default options with those provided.

// Note that the first Arg to extend is an empty object-

// This is to keep from overriding our "defaults" object.

VaR opts = $. Extend ({}, $. FN. hilight. defaults, options );

// Our plugin implementation code goes here.

};

// Plugin defaults-added as a property on our plugin Function

$. FN. hilight. defaults = {

Foreground: 'red ',

Background: 'yellow'

};

Now users can include a line like this in their scripts:

// This only needs to be called once and does not have to be called in the ready Block

$. FN. hilight. defaults. Foreground = 'blue ';

Next we can use the plug-in method like this, and it sets the blue foreground color:

$ ('# Mydiv'). hilight ();

As you can see, we allow users to write a line of code in the default foreground of the plug-in. You can also overwrite these new default values as needed:

// Overwrite the Default background color of the plug-in

$. FN. hilight. defaults. Foreground = 'blue ';

//...

// Call the plug-in using a new default setting

$ ('. Hilightdiv'). hilight ();

//...

// Pass the configuration parameters to the plug-in method to overwrite the default settings

$ ('# Green'). hilight ({

Foreground: 'green'

});

2.4 properly expose some functions

This section will expand your plug-ins step by step through interesting methods for the previous Code Section (while allowing others to expand your plug-ins ). For example, we can define a function named "format" in the implementation of the plug-in to format the highlighted text. Our plug-in now looks like this. The implementation of the default format method is under the hiligth function.

Java code

// Plugin Definition

$. FN. hilight = function (options ){

// Iterate and reformat each matched element

Return this. Each (function (){

VaR $ this = $ (this );

//...

VaR markup = javasthis.html ();

// Call our format Function

Markup = $. FN. hilight. Format (markup );

Export this.html (markup );

});

};

// Define our format Function

$. FN. hilight. format = function (txt ){

Return '<strong>' + TXT + '</strong> ';

};

We can easily support other attributes in the options object by allowing a callback function to overwrite the default settings. This is another great way to modify your plug-in. The trick shown here is to further effectively expose the format function so that it can be redefined. With this technique, others can pass their own settings to overwrite your plug-ins. In other words, others can also write plug-ins for your plug-ins.
Considering the useless plug-ins we have created in this article, you may want to know when these will be useful. A real example is the cycle plug-in. This cycle plug-in is a slide display plug-in that supports many internal transformations, such as scrolling, sliding, and fading. But in fact, there is no way to define the effects that may apply to each type of Slide change. That is where this scalability is useful.
The cycle plug-in exposes the "transitions" object to users so that they can add their own transformation definitions. The plugin is defined as follows:

$. FN. cycle. transitions = {

//...

};

This technique allows others to define and pass transformation settings to the cycle plug-in.

2.5 keep private functions

This technique exposes some of your plug-ins to be overwritten. But you need to think carefully about what is exposed in your implementation. Once exposed, you need to maintain any changes to the parameters or semantics in your mind may undermine backward compatibility. A general principle is that if you are not sure whether to expose a specific function, you may not need to do that. So how can we define more functions without disrupting namespaces or exposing implementations? This isClosure Functions. For demonstration, we will add another "debug" function to our plug-in. This
The debug function will output the selected element format to the firebug console. To create a closure, we define the entire plug-in as a function.

Java code

(Function ($ ){

// Plugin Definition

$. FN. hilight = function (options ){

Debug (this );

//...

};

// Private function for debugging

Function debug ($ OBJ ){

If (window. Console & window. Console. Log)

Window. Console. Log ('hilight selection count: '+ $ obj. Size ());

};

//...

}) (Jquery );

Our "debug" method cannot enter from external closures, so our implementation is private.

2.6 support for metadata plug-ins

Based on the plug-in you are writing, adding support for the metadata plug-in can make it more powerful. Personally, I like this metadata plug-in because it allows you to overwrite the plug-in options with a few "markup" plug-ins (this is useful when creating an example ). It is also very simple to support. Update: There are some optimization suggestions in the comments.

Java code

$. FN. hilight = function (options ){

//...

// Build main options before element Iteration

VaR opts = $. Extend ({}, $. FN. hilight. defaults, options );

Return this. Each (function (){

VaR $ this = $ (this );

// Build element specific options

VaR o = $. Meta? $. Extend ({}, opts, $ this. Data (): opts;

//...

These change lines do something: it is to test whether the metadata plug-in is installed. If it is installed, it can expand our options object by extracting the metadata line and adding it to jquery as the last parameter. extend, it will overwrite any other option settings. Now we can drive behavior from "markup". If we select "markup ":

You can write jquery. Foo (); or $. Foo ();

Java code

<! -- Markup -->

<Div class = "hilight {Background: 'red', foreground: 'white'}">

Have a nice day!

</Div>

<Div class = "hilight {Foreground: 'Orange '}">

Have a nice day!

</Div>

<Div class = "hilight {Background: 'green'}">

Have a nice day!

</Div>

Now we can highlight which divs only use one line of script:

$ ('. Hilight'). hilight ();

2.7 Integration
The code after the example is completed is as follows:

Java code // create a closure

(Function ($ ){

// Plug-in Definition

$. FN. hilight = function (options ){

Debug (this );

// Build main options before element Iteration

VaR opts = $. Extend ({}, $. FN. hilight. defaults, options );

// Iterate and reformat each matched element

Return this. Each (function (){

$ This = $ (this );

// Build element specific options

VaR o = $. Meta? $. Extend ({}, opts, $ this. Data (): opts;

// Update element styles

Export this.css ({

Backgroundcolor: O. background,

Color: O. Foreground

});

VaR markup = javasthis.html ();

// Call our format Function

Markup = $. FN. hilight. Format (markup );

Export this.html (markup );

});

};

// Private function: Debugging

Function debug ($ OBJ ){

If (window. Console & window. Console. Log)

Window. Console. Log ('hilight selection count: '+ $ obj. Size ());

};

// Define the exposure format Function

$. FN. hilight. format = function (txt ){

Return '<strong>' + TXT + '</strong> ';

};

// Defaults of the plug-in

$. FN. hilight. defaults = {

Foreground: 'red ',

Background: 'yellow'

};

// Closure ends

}) (Jquery );

This design allows me to create a powerful compliant plug-in. I hope it can also be done for you.

3. Summary

Jquery provides two methods for development plug-ins:

Jquery. FN. Extend (object); add a method to the jquery object.
Jquery. Extend (object); adds a new method to the class to extend the jquery class itself.

3.1 jquery. FN. Extend (object );

What is fn. It is not difficult to see jquery code.

Jquery. fn = jquery. Prototype = {

Init: function (selector, context ){//....

//......

};

It turns out that jquery. fn = jquery. prototype. It is certainly no stranger to prototype. Although JavaScript does not have a clear concept of a class, it is more convenient to use a class to understand it. Jquery is a well-encapsulated class. For example, we use the statement $ ("# btn1") to generate
Jquery class instance.

Jquery. FN. Extend (object); the extension to jquery. prototype is to add "member functions" to the jquery class ". Jquery class instances can use this "member function ".

For example, we want to develop a plug-in and create a Special edit box. When it is clicked, the content in the current edit box of alert is displayed. You can do this:

$. FN. Extend ({

Alertwhileclick: function (){

$ (This). Click (function (){

Alert ($ (this). Val ());

});

}

});

$ ("# Input1"). alertwhileclick (); // <input id = "input1" type = "text"/>

$ ("# Input1") is a jquery instance. When it calls the member method alertwhileclick, the extension is implemented. When it is clicked, the content in the current edit is displayed.

3.2 jquery. Extend (object );

Add a class method to the jquery class, which can be understood as adding a static method. For example:

$. Extend ({

Add: function (a, B) {return a + B ;}

});

Add a "static method" for jquery as add, and then you can use this method in the place where jquery is introduced,

$. Add (3, 4); // return 7

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.