How to write a jquery plugin

Source: Internet
Author: User

Reprinted from: http://blog.sina.com.cn/s/blog_6154bf970101jam7.html

With web development today, jquery is almost essential, and even the VS artifact has been built into the jquery and UI Web projects in version 2010. As for the use of jquery benefits here is not to repeat, used to know. Today we are going to discuss the jquery plug-in mechanism, jquery has thousands of third-party plug-ins, sometimes we write a separate function, but also want to combine it with jquery, you can use the jquery chain call, this will extend jquery, written in the form of plug-ins, as follows The polygon is a simple demo that extends the jquery object:

Sample: The method for extending the JQuery object, Bold () is used to bold the font.

(function ($) {

$.fn.extend ({

"Bold": function () {

The summary>

Bold font

The/summary>

Return This.css ({fontweight: "bold"});

}

});

}) (JQuery);
Call Mode:

This is a very simple extension. Next, we will parse the above code in one step.

First, the plug-in mechanism of jquery

To make it easier for users to create plugins, jquery provides the Jquery.extend () and JQuery.fn.extend () methods.

1. The Jquery.extend () method has an overload.

Jquery.extend (object), a parameter used to extend the jquery class itself, that is, to add a new function on the jquery class/namespace, or a static method, such as a jquery built-in Ajax method with Jquery.ajax () This is called a bit like "class name. Method Name" static method invocation. Let's also write an example of Jquery.extend (object):

Extending the jquery object itself

Jquery.extend ({

"MinValue": function (A, b) {

The summary>

Compares two values, returns a minimum value

The/summary>

return a B? A:B;

},

"MaxValue": function (A, b) {

The summary>

Compares two values, returns the maximum value

The/summary>

Return a > B? A:B;

}

});

Call

var i = 100; j = 101;

var Min_v = $.minvalue (i, j); Min_v equals 100.

var max_v = $.maxvalue (i, j); Max_v equals 101.
Overloaded version: Jquery.extend ([deep], Target, Object1, [objectn])

   extends an object with one or more other objects, returning the extended object.
   If target is not specified, the jquery namespace itself is extended. This helps plug-in authors add new methods to jquery.
   If the first argument is set to True, jquery returns a deep-seated copy that recursively replicates any objects found. Otherwise, the copy will share the structure with the original object.
   undefined properties will not be copied, but properties inherited from the object's prototype will be copied.
Parameters
  deep:       Optional. If set to True, the merge is recursive.
  target:     object to be modified.
  object1:   objects to be merged into the first object.
  objectN:   Optional. An object to be merged into the first object.
Example 1:
Merges settings and options, modifies and returns settings.
var settings = {validate:false, limit:5, Name: "foo"};
var options = {validate:true, name: "Bar"};
Jquery.extend (settings, options);
Result:
Settings = = {Validate:true, limit:5, Name: "Bar"}

Example 2:
Merge defaults and options without modifying the defaults.
var empty = {};
var defaults = {Validate:false, limit:5, Name: "foo"};
var options = {validate:true, name: "Bar"};
var settings = jquery.extend (empty, defaults, options);
Results:
Settings = = {Validate:true, limit:5, Name: "Bar"}
Empty = = {Validate:true, limit:5, Name: "Bar"}
This overloaded method, which we typically use to overwrite the default parameters of the plugin with custom plug-in parameters when writing a plugin.

JQuery.fn.extend (object) extends the set of jQuery elements to provide new methods (often used to make plug-ins).

First, let's see what FN is. If you look at the jquery code, it's not hard to find.

Jquery.fn = Jquery.prototype = {

Init:function (Selector, context) {...};
};

The original Jquery.fn =jquery.prototype, also known as the JQuery object prototype. The JQuery.fn.extend () method is the prototype method for extending the jquery object. We know that the method of extending the prototype is equivalent to adding a "member method" to the object, the class's "member method" to the object of the class to be called, so using the JQuery.fn.extend (object) extension method, an instance of the jquery class can use this "member function". The JQuery.fn.extend (object) and Jquery.extend (object) methods must be separated.

Second, self-executing anonymous function/closure

1. What is a self-executing anonymous function?
It is defined as a function like this: (function {//code}) ();
2. Question Why (function {//code}), can be executed, and function {//code} ();
3. Analysis
(1). First, be aware of the difference between the two: (function {//code}) is an expression, function {//code} is a functional declaration.
(2). Second, JS "precompiled" features: JS in the "pre-compilation" stage, will explain the function declaration, but will be suddenly token type.
(3). When JS executes to function () {//code} (), JS skips function () {//code} and attempts to execute () because function () {//code} has been interpreted in the "precompiled" stage;
When JS executes to (function {//code}) (), because (function {//code}) is an expression, JS will go to solve it to get the return value, because the return value is a function, therefore encountered (), it will be executed.

In addition, the method of converting a function to an expression does not necessarily depend on the grouping operator (), and we can also use the void operator, the ~ operator, and the operator ...

For example:
Plugin notation in the bootstrap framework:
!function ($) {
Do something;
} (JQuery);

And
(function ($) {
Do something;
}) (JQuery); is one thing.

The biggest use of anonymous functions is to create closures (which is one of the features of the JavaScript language), and you can also build namespaces to reduce the use of global variables.
For example:
var a=1;
(function () () {
var a=100;
})();
alert (a); Pop up 1

Three or one step by step package jquery Plugin

Next, let's write a highlight Jqury plugin.
1. Set a closure area to prevent the plug-in "pollution"

Closure-qualified namespaces

(function ($) {

}) (Window.jquery);
2.jquery.fn.extend (object) extends the JQuery method, making plugins
Closure-qualified namespaces

(function ($) {

$.fn.extend ({

"HighLight": function (Options) {

Do something

}

});

}) (Window.jquery);
3. Give plug-in default parameters, implement plug-in function
Closure-qualified namespaces

(function ($) {

$.fn.extend ({

"HighLight": function (Options) {

var opts = $.extend ({}, defaluts, options); overriding plug-in default parameters with Jquery.extend

This.each (function () {//Here is the jquery object

Iterate through all the DOM to be highlighted when calling the HighLight () plugin is a collection.

var $this = $ (this); Gets the current Dom's jquery object, where this is the DOM of the current loop

Set the DOM style according to the parameters

$this. CSS ({

BackgroundColor:opts.background,

Color:opts.foreground

});

});

}

});

Default parameters

Vardefaluts = {

Foreground: ' Red ',

Background: ' Yellow '

};

}) (Window.jquery);
In this step, the basic function of the highlight plugin is already available. The calling code is as follows:
$ (function () {

$ ("P"). HighLight (); Calling a custom Highlight plugin

});
This can only be called directly, not chained. We know that Jquey can be chained, that is, you can invoke multiple methods on a jquery object, such as:
$ (' #id '). CSS ({margintop: ' 100px '}). Addattr ("title", "Test");
However, the above plug-in, it can not be so chained to call. For example: $ ("P"). HighLight (). css ({margintop: ' 100px '});//will not find the CSS method, because the custom plug-in with me after the completion of the function, the jquery object is not returned. Next, the Returnjquery object, so that our plug-in also supports chaining calls. (In fact, it is very simple, that is, the implementation of our plug-in code when the jquery to return the image, and the above code is no different)
Closure-qualified namespaces

(function ($) {

$.fn.extend ({

"HighLight": function (Options) {

var opts = $.extend ({}, defaluts, options); overriding plug-in default parameters with Jquery.extend

Return This.each (function () {//This is the jquery object. Return here to support chained calls

Iterate through all the DOM to be highlighted when calling the HighLight () plugin is a collection.

var $this = $ (this); Gets the current Dom's jquery object, where this is the DOM of the current loop

Set the DOM style according to the parameters

$this. CSS ({

BackgroundColor:opts.background,

Color:opts.foreground

});

});

}

});

Default parameters

Vardefaluts = {

Foreground: ' Red ',

Background: ' Yellow '

};

}) (Window.jquery);
4. Exposing public methods to others to expand your plugin (if required)
For example, the highlight plugin has a format method to highlight the text, then we can write it as public, exposed to the plug-in users, different use of according to their own needs to rewrite the format method, so that the highlighted text can be rendered in different formats.
Public formatting methods. The default is bold, and the user can override the method to achieve different formatting effects.

$.fn.highlight.format = function (str) {

Return "strong>" + str + "/strong>";

}
5. Plug-in private methods
Sometimes, our plugins need some private methods that cannot be accessed by the outside world. For example, we need a method inside the plugin to detect whether the parameters passed in when the user invokes the plugin conform to the specification.
6. Other settings, such as: adding support for your plugin to the metadata plugin will make it more powerful.

The full highlight plugin code is as follows:

Closure-qualified namespaces

(function ($) {

$.fn.extend ({

"HighLight": function (Options) {

Checks whether the user passed in the parameter is legitimate

if (!isvalid (options))

return this;

var opts = $.extend ({}, defaluts, options); overriding plug-in default parameters with Jquery.extend

Return This.each (function () {//This is the jquery object. Return here to support chained calls

Iterate through all the DOM to be highlighted when calling the HighLight () plugin is a collection.

var $this = $ (this); Gets the current Dom's jquery object, where this is the DOM of the current loop

Set the DOM style according to the parameters

$this. CSS ({

BackgroundColor:opts.background,

Color:opts.foreground

});

Formatting highlighted text

var markup = $this. HTML ();

Markup = $.fn.highlight.format (markup);

$this. HTML (markup);

});

}

});

Default parameters

Vardefaluts = {

Foreground: ' Red ',

Background: ' Yellow '

};

A common format method. The default is bold, and the user can override the method to achieve different formatting effects.

$.fn.highlight.format = function (str) {

Return "strong>" + str + "/strong>";

}

Private methods to detect if the parameters are legitimate

Functionisvalid (options) {

return!options | | (Options && typeof options = = = "Object")? True:false;

}

}) (Window.jquery);
Call:
Call

Caller overrides common public method exposed by plugin

$.fn.highlight.format = function (TXT) {

Return "em>" + txt + "/em>"

}

$ (function () {

$ ("P"). HighLight ({foreground: ' Orange ', background: ' #ccc '});//Call a custom highlight plugin

});

How to write a jquery plugin

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.