JavaScript plugin development tutorial (1): javascript plugin

Source: Internet
Author: User

JavaScript plugin development tutorial (1): javascript plugin

I. Opening Analysis

Hi everyone! Today, this series of articles mainly talk about how to develop plug-in-type development based on "JavaScript". I think many people are familiar with the word "plug-in,

Some people may be called "components" or "components". This is not important. The key is to look at how to design and make a comprehensive consideration. This is the key concept of this article. I think

I have some knowledge about the "jQuery plug-in method". We will discuss it with this topic and finally provide the relevant implementation solutions to continuously improve my own capabilities.

2. Enter the plug-in subject

In general, jQuery plug-in development is divided into two types: one is the global function attached to the jQuery namespace, also known as the static method.

Another method is the jQuery object-level method, that is, the method attached to the jQuery prototype, so that the jQuery object instance obtained through the selector can also share the method.

(1) Development of class-level plug-ins

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 global function with the following definitions:

Copy codeThe Code is as follows:
$. Hello = function (){
Alert ("Hello, Xiong Jun! ");
};

1.2 add multiple global functions, which can be defined as follows:

Copy codeThe Code is as follows:
$. Extend ({
Hello: function (name ){
// Put your code here
},
World: function (){
// Put your code here
}
});

Note: "$. extend (target, [object1], [objectN]) "(This method is mainly used to merge the content (attributes) of two or more objects to the first object, and return the first object after merging.

If the method has only one target parameter, the parameter will expand the jQuery namespace, that is, the static method will be attached to the jQuery global object ).

(2) object-level plug-in development

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

2.1 "$. fn. extend ()" is used to dynamically attach attributes to the prototype.

Copy codeThe Code is as follows:
(Function ($ ){
$. Fn. extend ({
PluginName: function (opts ){
// Put your code here
}
});
}) (JQuery );

2.2 directly add dynamic attributes to the prototype chain.

Copy codeThe Code is as follows:
(Function ($ ){
$. Fn. pluginName = function (){
// Put your code here
};
}) (JQuery );

Note: The two are equivalent. For a jQuery plug-in, a basic function can work well, but for a complicated plug-in, various methods and private functions need to be provided.

You may use different namespaces to provide various methods for your plug-ins. However, adding too many namespaces will make the code messy and robust. Therefore, the best solution is to properly define private functions and methods.

Therefore, we use the combination of self-executed functions and closures to simulate private plug-in units, just like in our above instance.

(3) let's take a simple example to see the implementation process:

(1) The "html" snippet code is as follows:

Copy codeThe Code is as follows:
<Div id = "bb" style = "width: 220px; border: 1px solid # ccc;">
<Span> </span>
<Div
Style = "margin-top: 10px;
Margin-bottom: 30px ;"
> 8 </div>
</Div>

(2) "data. json" is defined as follows:

Copy codeThe Code is as follows:
{
"Text": "Hello, Xiong Jun {bb }}! ";
}

(3) The "bb. js" code is as follows:

Copy codeThe Code is as follows:
$ (Function (){
$ ("# Bb"). bigbear ();
});
(Function ($ ){
$. Fn. bigbear = function (opts ){
Opts = $. extend ({}, $. fn. bigbear. defaults, opts );
Return this. each (function (){
Var elem = $ (this );
Elem. find ("span"). text (opts ["title"]);
$. Get (opts ["url"], function (data ){
Elem. find ("div"). text (data ["text"]);
});
});
};
$. Fn. bigbear. defaults = {
Title: "This is a simple test ",
Url: "data. json"
};
}) (JQuery );

Running effect:

Summary:

(1) "$. fn. bigbear. defaults provides default parameter options for the plug-in. A well-scalable plug-in should allow users to customize Parameter options as needed and control the behavior of the plug-in, therefore, it is necessary to provide the default recovery options. You can use the extend method of jQuery to set these options.

(2), "return this. each (){...} "traverses multiple elements and returns jQuery using the Sizzle selector engine. Sizzle can provide multi-element operations for your function (for example, for all elements with the same class name ). This is one of jQuery's several excellent features. It is still a good way to prepare for the plug-in even if you are not prepared to provide multi-element support for your plug-in during development. In addition, jQuery has a good feature that it can perform method cascade or chained call. Therefore, we should not destroy this feature and always return an element in the method.

(4). Conclusion

(1) jQuery provides two methods for development plug-ins: jQuery. fn. extend (object); and adds methods to jQuery objects.
JQuery. extend (object); adds a new method to the class to extend the jQuery class itself.

(2) Place all the code in the closure (an immediate execution function). At this time, the closure is equivalent to a private scope, and internal information cannot be accessed from the outside, and there will be no contamination of global variables. The official development specifications are as follows: a) avoiding global dependencies; B) avoiding third-party damages; c) compatible with jQuery operators '$' and 'jQuery '.

(3) provide default parameter options for plug-ins. A well-scalable plug-in should allow users to customize Parameter options as needed and control the behavior of plug-ins, therefore, it is necessary to provide the default recovery options. You can use the extend method of jQuery to set these options.

(4) traverse multiple elements and return jQuery using the Sizzle selector engine. Sizzle can provide multi-element operations for your function (for example, for all elements with the same class name ). This is one of jQuery's outstanding features. It is still a good practice to prepare for the plug-in even if you are not prepared to provide multi-element support for the plug-in during development. In addition, jQuery has a good feature that it can perform method cascade or chained call. Therefore, we should not destroy this feature and always return an element in the method.

(5) It is very important to put one-time code out of the main loop, but it is often ignored. To put it simply, if you have a piece of code with a bunch of default values, you only need to instantiate it once, instead of instantiating it every time you call your plug-in function, you should put this code out of the plug-in method.

(6) After learning and thinking, if the project technology selection changes to these plug-ins, they are strongly dependent on the "jQuery" mechanism, the plug-ins we previously wrote will not be available (assuming jQuery is not used). How can we refactor them?

Tomorrow's article will discuss this issue and rebuild the key logic of the plug-in...

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.