jquery Create your own plug-in (custom plug-in) method _jquery

Source: Internet
Author: User
Tags closure extend locale
But it must be known that these plug-ins are not produced by themselves, they are made by DevelopmentPeople write, test, and refine these people for jQuery CommunityDevote one's spare time. We do this for free, out of love for our own code. This article focuses on how you can repay this great community, how to write your own plug-ins and upload them to JQuery's plugin page. This allows everyone to use the plug-ins you create to make the entire jQuery development community better. You also make your contribution this year.

As I write the plug-ins in this article, I find that the process of creating plug-ins and the framework used to create them is very straightforward. The hard part is thinking about things that others haven't done, and writing JavaScript code that can actually do something. Because the plug-in structure is simple and clear, for beginners it is easy to learn, for the master it is very flexible, so the number of plug-ins increased rapidly.

Of course, in studying the content of this article, I also found that each author has a different style of writing plug-ins, JQuery allows several different types of plug-ins to write style. In this article, I'll focus on the simplest style, and the style recommended by JQuery itself, and you'll see the difference or different options when the plugin pops up.

Description Plugin

The 1th step in creating a plugin is of course to think of a good idea. Like most ideas, other people always create opportunities for you. The plugin I developed in this article, for example, is not a novel concept, but it was not found in the JQuery plug-in community when I wrote the text. I know I personally will benefit a lot from this plugin.

My plugin is a numberformatter plugin. Processing Server -side code (such as Java™ or PHP) and internationalized users should be familiar with digital formatting. It is well known that not everyone formats numbers in the same way. For example, not everyone uses "Li" to measure distances. In the United States, the number may be written as "1,250,500.75" (this number is copied from my tax form), but in other countries the wording may be completely different: Germany is "1.250.500,75", France is "1 250 500,75", Switzerland is "1 ' 250" 500.75 ", Japan is" 125,0500.75 ". The numbers are exactly the same, but you use different formats when presenting to Web application users.

So the question boils down to how do you show these numbers to people from different countries when you are writing an internationalized application? Of course, the solution is to use server-side formatting, which is very common. Java has a robust format library that makes the formatting of numbers very simple. When you use numbers to set up a page on a server, the server handles these numbers. However, many times the numbers may not be on the server, so you need a way to format the numbers on the client without having to talk to the server.

The typical use cases I describe here are as follows. There is an input field in your Web application that asks the user to enter their salary. In the United States, users may enter "$65000", "65,000", "65000" and "65,000.00" in various formats. All of these numbers are the same, but you need to control how these numbers are displayed on the screen to provide a better user experience. You can call the server after you enter a number, but it's too cumbersome to have many numeric fields with different formats. In addition, if you can handle the problem on the client and provide immediate feedback to the user, then you do not need to do so.

So I set up a vacancy and then I will try to fill this vacancy with the Javascript/jquery feature . My plug-in will provide a number format on the client and provide a way for others to internationalize the Web application without having to talk to the server. As an additional feature, my plug-in can also provide a reverse operation that enables developers to parse numbers and get numbers from formatted text strings. This can also be applied to numeric operations on the client computer. In addition, I will simulate DecimalFormatter the functionality in the Java class to maintain commonality between the client code that performs the number formatting and the standard server-side methods.

The 1th result: I found a plugin requirement and then defined the vacancy I could fill for that requirement.

Plug-in rules

The JQuery team built a common and trusted environment for plug-in users by creating a number of common rules that they want the plugin authors to follow. Given that the JQuery team is a lot smarter than I am, I have no reason to violate these rules, right? For that reason, I list these rules here and try to comply with them at every step of the plug-in.

  • The file is named " jquery.<your plug-in name>.js "
    This makes sense because you want the user to see the file as soon as they know it is a jQuery plug-in and which plugin it is.

    Check complete. My plugin will be named " jquery.numberformatter.js ".

  • All new methods are attached to the Jquery.fn object , all new features are attached to the JQuery object
    This may be a bit hard to understand at this stage, and I'll talk more about it in the next section because it's the most important rule in the actual coding process.

    Check complete. My methods/functions will only be attached to these two objects.

  • " this " to refer to the JQuery object
    This facilitates the authoring of plug-in authors, which allows all plug-in authors to this know which object will be received from JQuery when referring to "".

    Check complete. I'll only use " this " to refer to the JQuery object.

  • The end of all methods/functions defined in the plug-in must be preceded by a ";" (semicolon), otherwise it will not be conducive to the minimization of the code.
    Because this is the best practice for minimizing JavaScript files, it's much worse than the minimum, and your plug-in may soon be discarded.

    Check complete. All methods/functions will end with ";".

  • All methods must return the JQuery object except as specifically noted
    The order chain (daisy-chaining) of the JQuery method is very famous, and if you write a plug-in that breaks the chain, it will definitely "break the chain".

    Check complete. My format() method will return the jquery object, although my parse() method does not return the jquery object, but I have indicated in many places that the function broke the chain. (After all, it is not possible to return a number object without breaking the chain).

  • You should always use an this.each() iteration-matching element, which is a reliable and efficient way to iterate over an object.
    For performance and stability reasons, they recommend that all methods use it to iterate over the matching elements.

    Check complete. My method will only use the method to iterate through the matching elements.

  • Always use "jQuery" instead of "$" in your plug-in code
    This is important to enable users who have conflicting "$" (those who use another JavaScript library) to use the var JQ = jQuery.noConflict(); function to change their jQuery alias (pseudonym). However, when I looked at many plug-ins, I found that the rule was often not adhered to, which is unfortunate. If a developer needs to change the JQuery alias, it probably means that the plugin will be discarded.

    Check complete. In my plugin, I will only use jQuery instead of its alias "$".

Well, these are the rules and recommendations that you must follow in your plug-in code. The real problem is that they are actually mandatory, because if you don't follow these plug-in rules, your plugin won't be widely used, and you'll get bad feedback. As a result, the plugin is no longer available to anyone, and the time you spend will be in vain. It is therefore important to comply with these rules. This will not only help you stand out from the crowd, guarantee the uniformity of your code, but also increase your plug-in's chances of success.

Step 2nd: I'll follow all the rules for creating JQuery plug-ins

Writing Plug-ins

Now it's time to start writing code! The first step in writing a plug-in is to determine how your plug-in is organized. There are two options at the beginning: Do you want it to be a method or a function? "Do they have a difference?" "You might ask that.

As I mentioned above, the method needs to be attached to the Jquery.fn object, and the function needs to be attached to the JQuery object. It 's all clear, isn't it? If you are relatively less knowledgeable about jQuery, it may not be clear. You can consider this. Method enables code to iterate through the selected elements of all incoming plug-ins. Therefore, Plug-ins can receive any type of HTML element, and the plug-in determines how each element is handled. Therefore, the plug-in method can receive any JQuery selector, all from "P" to "#mySpecificPageElement" content. If you want the plug-in to be more flexible and allow the user to pass in any type of page element, it is best to use the method. The plug-in developer should be responsible for handling all content correctly. By contrast, a function does not use any of the selected elements as arguments. Functions can be applied simply to the entire page. This is also handled by the plug-in developer, who must define the page elements that they want to interact with the plug-in and ignore the other elements. Let's look at the differences in the code.


Listing 1. JQuery Plug-in Methods/functions

//this are a method because you can pass any type of selector to the and it
// Would take some action on the results of the selector. In this case, it would
//dosomething () on the page element with a ID of Myexample
$ ("#myExample"). DoSomething ();

//This are also a method, even though you are passing the entire page body to
//the method, because you are still Passing a selector
$ ("body"). Dosomethingelse ();

 

//is a function, because your are not passing any selector to the function
//The plug-in developer must INE what page elements they want to take action on.
//This are usually accomplished by the plug-in developer requiring the page elements
/to contain a certain class Name.

<div class= "anotherthing"

//This hypothetical plug-in developer would document that he plug-in only works
//In elements with the class "Ano Therthing "
$.anotherthing ();

Judging from these descriptions, Plug-ins seem to use methods, because you need to let users tell you which page elements they want to format. Listing 2 shows the code for the plug-in now.


Listing 2. Method definition

JQuery.fn.format = function ();

You are would call your plug-in as this
$ ("#myText"). Format ();

Of course, your function is unlikely to be a universal plug-in because you are dealing with an internationalization situation and cannot automatically indicate the country or format you want to format the text. Therefore, you must modify the plug-in slightly to receive certain options. Two options are required in the Format method: the format that the number should use (for example, #,### and #,###.00) and the local locale (the local locale is a simple 2-word Fu Home code that determines the international number format to use).

You also need to make the plug-in as easy to use as possible, because you have to improve the success of your plug-in. This means that you should continue to define some default options so that users do not need to do so when they do not want to pass in an option. My plugin is located in the United States, where the world's most common number format, my default locale is "us", the format defaults to "#,###.00", so the currency will naturally use the default value.

Listing 3. Allow options to be used in Plug-ins


JQuery.fn.format = function (options) {

The Jquery.extend function takes a unlimited number of arguments, and each
Successive argument can overwrite the values of the previous ones.
This are beneficial for defining default values, because to you define
them, and then use the options passed to the method as the
Second argument. This allows the "user to" override any default values with their
Own in a easy-to-use setup.
var options = Jquery.extend ({

Format: "#,###.00",
Locale: "Us"

}, Options);

The last step in creating the plug-in framework is to correctly handle the selected elements of the incoming method. Think back to the example above you will find that the selected element can be a single page element or a multiple page element. You must treat them equivalently. Again, recall the jquery plug-in rule that "this" objects can only reference jquery objects. Therefore, you have a reference to the JQuery selected element of the Passed-in method, and you now need to iterate over them. Again, the retrospective rules let us know that each plug-in method should return the JQuery object. Of course, you know the JQuery object "this" , so it's completely fine to return this in the method. Let's see how to implement each selected element in the code fragment and return the JQuery object.


Listing 4. Working with JQuery objects


JQuery.fn.format = function (options) {

var options = Jquery.extend ({

Format: "#,###.00",
Locale: "Us"

}, Options);

This code snippet would loop through the selected elements and return the JQuery object
When complete
Return This.each (function () {
Inside each iteration, you can reference the current element by using the standard
JQuery (This) notation
The rest of the plug-in code goes here
});

Since the actual plug-in itself is not the focus of this article, I do not elaborate on this, but you can see all of the content in the plug-in code attachment in this article (see download). If you decide to write a function instead of a method, I'll show you a sample of how to set up the plug-in schema.


Listing 5. Example plug-in using a function


jquery.examplefunction = function (options) {

var options = Jquery.extend ({

Your defaults

}, Options);

JQuery (". Exampleselector"). each (function () {

});

});

Tuning Plug-ins

This is the end of most articles on the web for beginners, which let you use the basic plug-in format and run it. However, this basic structure is too "basic". Another important thing to think about when writing plug-ins is that the content you need to add color to your plug-in is much more than a single primary plug-in. With an additional two steps, you can convert the primary plug-in to a medium-level plugin.

Tuning #1-Privatization of internal methods

In any object-oriented programming language, you'll find it convenient to create external functions that run duplicate code. In the Numberformatter plug-in I created, there is a sample of this code that determines which geography to pass to the function, and which characters to use as decimal and group character. format() parse() The code is needed in both methods and methods, and any novice programmer will tell you that this is its own method. However, this can be a problem because you are dealing with a JQuery plug-in: If you use the definition in JavaScript as your own function, anyone can invoke the method with a script for any purpose. This is not the purpose of the function, I prefer not to call it, because it is only for internal work. So, let's see how to privatize this function.

The solution to this private method problem is called Closure, which effectively closes the entire plug-in code from an external invocation, except for the JQuery object (those are public methods). With this design, you can put any code into the plug-in without fear of being invoked by an external script. By attaching plug-in methods to JQuery objects, you can effectively turn them into public methods and let other functions/classes privatize. Listing 6 shows the code needed to implement the operation.


Listing 6. privatization function


This code creates the Closure structure
(function (jQuery) {

This function is "private"
function Formatcodes (locale) {
Plug-in specific code here
}; Don ' t forget the semi-colon

This is "public" because it's attached to the JQuery object
JQuery.fn.format = function (options) {

var options = Jquery.extend ({

Format: "#,###.00",
Locale: "Us"

},options);

Return This.each (function () {
var text = new String (JQuery (this). text ());
if (JQuery (this). Is (": Input"))
Text = new String (JQuery (This). Val ());

Can call the private function like any other function
var formatdata = Formatcodes (Options.locale.toLowerCase ());

Plug-in-specific code here
});
}; Don ' t forget the semi-colon to close the method

This code ends the Closure structure
}) (JQuery);


Tuning #2-Let the default value of the plug-in be overwritten

The final step in tuning the plug-in is to allow it to override the default values. After all, if a German developer downloads the plugin, and all of his web application users want to use the German version, you should let him use one line of code to modify the default locale instead of having to modify it in every method call. This makes your plug-in very handy, because a Web application is less likely to display numbers to users in different internationalized formats. As you can see on the Web page, all numbers are in the same locale format.

This step requires you to modify some code, so you will see the most dazzling step of making plug-ins.


listing 7. Overriding default values

 

JQuery . Fn.format = function (options) {
//change how do you load your options in to take advantage of your overridable defaults< br>//you your extend () function works, because the defaults
//are globally defined, rather than within the Method. If you are didn ' t use the
//{} as the the ' argument ', you ' d copy the options passed in over the defaults, which is
//U Ndesirable. This {} Creates a new temporary object to store the options
//can simply call the defaults as an object within R plug-in
var options = jquery.extend ({},jquery.fn.format.defaults, options);

Return This.each (function () {

//Rest of the plug-in code is here

//define the defaults as a object in The plug-in
JQuery.fn.format.defaults = {
Format: "#,###.00",
Locale: "Us"
};//don ' t forget the semi-colon


This is the last step in creating a plugin! So you have a good plug-in, you can do the final test. Listing 8 shows the complete plugin that you can put into this article so that you see how these parts become a whole. Also included is the parse() function, which I haven't discussed so far, but it's included in the plug-in (I don't have a detailed description of the plug-in processing format because they are not covered in this article). This part is included in the sample, and the plugin itself is of course.


Listing 8. Numberformatter plugin

(function (jQuery) {

function Formatdata (valid, Dec, group, neg) {
This.valid = valid;
This.dec = Dec;
This.group = Group;
This.neg = neg;
};

function Formatcodes (locale) {
Format logic goes here
return new Formatdata (valid, Dec, group, neg);
};

JQuery.fn.parse = function (options) {

var options = Jquery.extend ({},jquery.fn.parse.defaults, options);

var formatdata = Formatcodes (Options.locale.toLowerCase ());

var valid = Formatdata.valid;
var dec = Formatdata.dec;
var group = Formatdata.group;
var neg = Formatdata.neg;

var array = [];
This.each (function () {

var text = new String (JQuery (this). text ());
if (JQuery (this). Is (": Input"))
Text = new String (JQuery (This). Val ());


Now we are need to convert it into a number
var number = new Number (Text.replace (group, '). Replace (Dec, "."). Replace (neg, "-"));
Array.push (number);
});

return array;
};

JQuery.fn.format = function (options) {

var options = Jquery.extend ({},jquery.fn.format.defaults, options);

var formatdata = Formatcodes (Options.locale.toLowerCase ());

var valid = Formatdata.valid;
var dec = Formatdata.dec;
var group = Formatdata.group;
var neg = Formatdata.neg;

Return This.each (function () {
var text = new String (JQuery (this). text ());
if (JQuery (this). Is (": Input"))
Text = new String (JQuery (This). Val ());

Formatting logic goes here

if (JQuery (this). Is (": Input"))
JQuery (This). Val (returnstring);
Else
JQuery (This). Text (returnstring);
});
};

JQuery.fn.parse.defaults = {
Locale: "Us"
};

JQuery.fn.format.defaults = {
Format: "#,###.00",
Locale: "Us"
};

}) (JQuery);


Test Plug-in

The final step in creating a plug-in is to test it thoroughly. Users find bugs in plug-ins that annoy them. Users are not going to fix it and they will quickly give up using it. If you have a few of these users with some bad comments, your plugin will soon be down the drain. In addition, this is a good reciprocal behavior-you want to use the plug-ins you have been well tested, then you should also provide a well tested plug-ins.

I created a quick test structure to test my plug-in (without the need for a unit test library), which created many spans, some numbers in the spanned, and the correct format for the number immediately following the number. The JavaScript test formats the numbers, then compares the formatted numbers with the desired results, and displays red if they fail. With this test, I can set up different test cases and test all possible formats (I've already done this). I attached the test page to the sample download so that you could find a possible solution to test your plug-in and use JQuery to test it.

To view completed Plug-ins

Let's look at the new Numberformatter in motion. I've created a simple Web application that lets you see how the Numberformatter plug-in meets your application.

Figure 1. Numberformatter in Operation

This WEB application is simple and straightforward. When a user leaves a text field (after entering salary, home, and child information), the Numberformatter plug-in formats the information it enters accordingly. This plug-in enables a WEB application to present a uniform format of numbers to the user. Also note that the Web application is formatted for the German user, so the decimal and grouping symbols are not the same as American users (for this, let me show you how to change the default values).


listing 9. Numberformatter in Operation

$ (document). Ready (function () {

Use the alphanumeric plug-in to limit the input
$ (". Decimal"). Decimal ();
$ (". Numeric"). numeric ();

You are want to the "defaults" to the German locale
This'll change the default for every
Entire page, so you won ' t have ' "locale"
argument to any function
$.fn.format.defaults.locale = "de";
$.fn.parse.defaults.locale = "de";

When the salary field loses focus, format it properly
$ ("#salary"). blur (function () {
$ (this). Format ({format: "#,###.00"});
});

When the House field loses focus, format it properly
$ ("#houseWorth"). blur (function () {
$ (this). Format ({format: "#,###"});
});

When the kids field loses focus, format it properly
$ ("#kids"). blur (function () {
$ (this). Format ({format: "#"});
});

Calculate the tax
$ ("#calculate"). Click (function () {
Parse the numbers from the fields
var salary = $ ("#salary"). Parse ();
var house = $ ("#houseWorth"). Parse ();
var kids = $ ("#kids"). Parse ();
Make some imaginary tax formula
var tax = Math.max (0, (0.22*salary) + (0.03*house)-(4000*kids));
Place the result in the Tax field, and then format the resulting number
You need one intermediate step though, and that ' s the ' formatnumber ' function
Because all numbers in JavaScript with a US locale when made into a String
You are need to convert this number into a German locale String before
Calling format on it.
So, the steps are:
1) The tax is a number this looks like 9200.54 (US locale)
2) FormatNumber converts this to a String of 9200,54 (German locale)
3 Put this String in the #tax field
4) call Format () on the This field
$ ("#tax"). Text ($.formatnumber (tax)). Format ({format: "#,###"});
});

});


Before closing, there are a few things to point out about the Numberformatter plug-in. First, the plug-in is the first 1.0.0 release, so I want to extend it in the future, including more formatting in the Java decimalformatter. Includes support for currency, scientific notation, and percentages. It also contains different formatting rules for negative and positive numbers, which are not simple "-" (for example, for negative numbers (5,000), as in accounting). Finally, a good formatter should support any character in the format, and only it ignores parts that are not part of the reserved character. These are the features I want to add in the near future, and I want the plugin to be more robust.

Get the user's language environment

The last question has nothing to do with jQuery, but it may appear when you use the plugin-how do I get the user's locale? This is a good question because there is no way to get this information using JavaScript at the moment. You need to create a JavaScript bridge for that purpose. What is JavaScript Bridge? I mean you can create a simple design pattern to pass values from server-side code to JavaScript code. Listing 10 shows how you can use Java to do this on a JSP page.

listing 10. Getting the user's language environment

<%

The request object is built into JSPs
Unfortunately, it ' s not any easier
Tested on FF, IE, Safari, Chrome
String locale = "US"; or your default locale
String Acclang = Request.getheader ("Accept-language");
if (Acclang.length () > 5)
{
Acclang = acclang.substring (0,5);
Locale = acclang.substring (Acclang.indexof ("-") +1);
}

%>

$ (document). Ready (function () {

Take advantage of the ability to override defaults by using the JavaScript
Here's bridge. Then your page can use the format () and parse () functions
Elsewhere in the page without modifying them for a user ' s locale.
$.fn.format.defaults.locale = "<%=locale%>";
$.fn.parse.defaults.locale = "<%=locale%>";

});


Shared plugins

Finally, write and test plug-ins are done. The final step is to share the plugin with others and upload it to the plug-in repository on the JQuery Web site.

    • Go to the plugin page of the JQuery Web site, in the left navigation bar, click login/register and then click Create Newaccount. If you already have an account, log in or, if not, create a new account.
    • After validation is passed, the left navigation will appear with some options. There is an "Add plug-in".
    • The navigation plug-in creates the page. Because you can only test the plug-in with JQuery 1.2, you should include it as a compatible version. Take some time to write a good title and a good description for the plugin. After all, it's time to sell the plugin to other users, and you need to differentiate yourself. Try to speak out the benefits of the plugin.
    • This plugin requires you to provide the plugin home page. Although you created a plug-in, you probably don't have a plugin home page. Fortunately, if you don't have your own server-saving plugin, Google is happy to provide space for open source projects. I chose to place the plugin in Google Code. To create your own Google Code project, you only need to access code.google.com and register with the registration process.
    • When you press Submit , your plugin is created!
      Congratulations, your plugin is now part of the JQuery plug-in community, and you are now officially one of the contributors to the open source project. Give yourself a 5 star rating to reward yourself! Because you deserve it!

Conclusion

In this article, I'm mainly talking about creating plug-ins for the JQuery JavaScript framework. I started from scratch, conceived an idea and put it into practice, and described several steps to use to create the plug-in. I then read the JQuery "Commandment", which is a plug-in rule set up to ensure the consistency of plug-ins. I also reminded these rules in the article because I saw that many of the rules were not adhered to in plug-ins, especially the use of "jQuery" instead of "$" in plug-ins (I followed that rule, of course).

After describing the background of the plug-in and the rules for writing plug-ins, you learned about the basic plug-in framework and how to write a method in a plug-in that differs from writing a function. method should be used when taking the selected element as a parameter and performing certain operations on it. The task of providing page elements is the responsibility of the person calling the method. On the other hand, the function should be used when it is not interested in the selected element, because you already know the page element on which to perform the action. The task of providing page elements is the responsibility of the developer who wrote the function. Both forms of plug-ins are valid and differ only on plug-in requirements. Finally, see the basics of setting the default options and how to get users to provide their own options.

The next step in this article is to provide some highlights for plug-ins to increase its sophistication. This step draws a full stop to the entire plug-in, effectively creating private functions and public functions. I created some functions that were called inside the plug-in so that people outside the plug-in could not call them. You can also see how to show the default values to the plug-in user, let the user define their own defaults, and easily encode.

Finally, use Plug-ins in the sample Web application to demonstrate its behavior. The final part of this article is the end result of these hard work-you need to upload the plugin to the JQuery plug-in community site and make it part of the JavaScript library.

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.