jquery Plug-in Write steps detailed _jquery

Source: Internet
Author: User
Tags closure extend

This example describes the jquery plug-in authoring step. Share to everyone for your reference, specific as follows:

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

Sample: Method for extending the JQuery object, Bold () for bold fonts.
(function ($) {
  $.fn.extend ({
    "bold": function () {
      ///<summary>
      ///bold font
      ///</ summary> return
      this.css ({fontweight: "bold"});})
(JQuery);

Call Mode:

This is a very simple extension. Next, we'll parse the code in the first step.

One, jquery plug-in mechanism

To facilitate user-created Plug-ins, jquery provides 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, which is used to add new functions to the JQuery class/namespace, or static methods, such as jquery's built-in Ajax methods are all Jquery.ajax () This calls a bit like the way the static method of the class name. Method name is called. Let's write an example of Jquery.extend (object) here:

Extends the JQuery object itself
jquery.extend ({
  "MinValue": function (A, b) {
    ///<summary>
    ///compares two values, returns the minimum value
    ///</summary> return
    a < b a:b;
  },
  "MaxValue": function (A, b) {
    ///<SUMMARY>
   ///compares two values, returns a maximum value
    ///</summary> return
    a > b a:b;
  }
);
Call
var i = n. J =;
var Min_v = $.minvalue (i, j); Min_v equals
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 object being extended.
If target is not specified, the jquery namespace itself is extended. This helps the plugin author add new methods for jquery.
If the first argument is set to True, jquery returns a deep copy, recursively copying any objects found. Otherwise, the copy will share the structure with the original object.
Undefined properties will not be replicated, but properties inherited from the object's prototype will be replicated.

Parameters:

Deep: Optional. If set to True, recursion is merged.
Target: object to be modified.
Object1: The object to be merged into the first object.
OBJECTN: Optional. The object to merge to the first object.

Example 1:

Merge settings and options, modify and return to settings.

var settings = {validate:false, limit:5, Name: "foo"};
var options = {validate:true, name: "Bar"};
Jquery.extend (settings, options);

Results:

Settings = = {Validate:true, limit:5, Name: "Bar"}

Example 2:

Combine 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 is commonly used to overwrite the default parameters of Plug-ins with custom plug-in parameters when writing Plug-ins.

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

First, let's see what FN is. See the jquery code, it's not hard to find.

Jquery.fn = Jquery.prototype = {
  Init:function (selector, context) {...};


The original Jquery.fn = Jquery.prototype, which is the prototype of the JQuery object. The JQuery.fn.extend () method is to extend the prototype method of 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 can be invoked, 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 distinguished.

Self-executed anonymous function/closure

1. What is a self executing anonymous function?

It refers to a function such as this:

(function {//code}) ();

2. Question Why (function {//code}); can be executed, and function {//code} ();

3. Analysis

(1). First, be clear about the difference between the two:

(function {//code}) is an expression, function {//code} is a declaration of functions.

(2). Second, JS "precompiled" features:

JS in the "precompiled" phase, will interpret the function declaration, but will be a slight.

(3). when JS executes to function () {//code} (), because function () {//code} has been interpreted in the precompiled phase, JS skips function () {//code} to attempt to execute ();
When JS executes to (function {//code}), because (function {//code}) is an expression, JS will be able to solve it to get the return value, because the return value is a function, and 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 (), we can also use the void operator, the ~ operator ...

For example:

Bootstrap in the framework of the plug-in:

!function ($) {
//do something;
} (JQuery);

And

(function ($) {
//do something;
}) (JQuery);

is one thing.

The biggest use of anonymous functions is to create closures, which are one of the features of the JavaScript language, and to 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 encapsulation jquery Plugin

Next, we'll write a highlighted Jqury plugin.

1. Set a closure area to prevent the plug-in "pollution"

Closures qualify Namespaces
(function ($) {
}) (Window.jquery);

2.jquery.fn.extend (object) extends the JQuery method, making Plug-ins

Closures qualified namespaces
(function ($) {
  $.fn.extend ({
    "highlight": function (options) {
      //do something
    }
  });
}) (Window.jquery);

3. To the plug-in default parameters, to achieve the function of Plug-ins

Closures qualify Namespaces
(function ($) {
  $.fn.extend ({
    "highlight": function (options) {
      var opts = $.extend ({}, Defaluts, Options); Use Jquery.extend to overwrite plug-in default parameters
      This.each (function () {//This is the jquery object
        //Traversal of all the DOM to be highlighted when calling highlight () The plugin is a collection of time.
        var $this = $ (this);//Get the jquery object for the current DOM, where this is the DOM//per parameter of the current loop
        to set the style of the Dom
        $this. css ({
          BackgroundColor:opts.background,
          color:opts.foreground
  }
  );}); Default parameter
  var defaluts = {
    foreground: ' Red ',
    background: ' Yellow '
  }
(Window.jquery);

To this point, the basic functionality of the highlighted plug-in is already available. The calling code is as follows:

$ (function () {
  $ ("P"). Highlight ();//Invoke custom highlighting
});

This can only be called directly and cannot be chained to the call. We know that Jquey can be called by chain, that is, you can invoke multiple methods on a jquery object, such as:

$ (' #id '). CSS ({margintop: ' 100px '}). Addattr ("title", "Test");

But the plugin above, we can't do this chained call. Like what:

$ ("P"). Highlight (). CSS ({margintop: ' 100px '});

The CSS method will not be found because the jquery object was not returned to my custom plug-in after completing the feature. Next, return the jquery object and let our plugin also support chained calls. (In fact, it's simply that when you're done with our plug-in code, you return the jquery to the same thing as the code above).

Closures qualify Namespaces
(function ($) {
  $.fn.extend ({
    "highlight": function (options) {
      var opts = $.extend ({}, Defaluts, Options); Overwrite the plug-in default parameter with Jquery.extend return
      This.each (function () {//This is the jquery object. Return here to support chained calls
        //traversal of all the DOM to be highlighted when calling the highlight () plug-in is a collection.
        var $this = $ (this);//Get the jquery object for the current DOM, where this is the DOM//per parameter of the current loop
        to set the style of the Dom
        $this. css ({
          BackgroundColor:opts.background,
          color:opts.foreground
  }
  );}); Default parameter
  var defaluts = {
    foreground: ' Red ',
    background: ' Yellow '
  }
(Window.jquery);

4. Exposing public methods to others to extend your plugin (if there is a need)

For example, the highlighting plugin has a format method for formatting words highlighted text, then we can write it as a public, exposed to the plug-in users, different use of their own needs to rewrite the format method, so that the highlighted text can be rendered in different formats.

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>";
}

5. Plug-in Private method

In some cases, our plug-ins need some proprietary methods that cannot be accessed by the outside world. For example, we need to have a method inside the plug-in to detect when the user invokes the plug-in parameters passed in compliance with the specification.

6. Other settings, such as: support for your plug-in to add metadata plug-ins will make it more powerful.

The complete highlighted plug-in code is as follows:

The closure qualifies the namespace (function ($) {$.fn.extend ({"Highlight": function (Options) {///check whether the parameter passed by the user is legal if (!isvali)
      d (Options)) return to this; var opts = $.extend ({}, defaluts, options); Overwrite the plug-in default parameter with Jquery.extend return This.each (function () {//This is the jquery object.
        Return here to support chained calls//traversal of all the DOM to be highlighted when calling the highlight () plug-in is a collection. var $this = $ (this); Gets the jquery object for the current DOM, where this is the DOM//per parameter of the current loop to set the DOM's style $this. css ({BackgroundColor:opts.backgro
        und, color:opts.foreground});
        Format highlighted text var markup = $this. HTML ();
        Markup = $.fn.highlight.format (markup);
      $this. HTML (markup);
    });
  }
  });
  Default parameter var defaluts = {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 method, detection parameter is legal function isValid (options) {return!options | | (Options && typeof options = = "Object")?
  True:false;

 }) (Window.jquery);

Call:

Call
//caller overwrite plug-in exposed common method
$.fn.highlight.format = function (TXT) {return
  "<em>" + txt + "</em>" 
   }
$ (function () {
  $ ("P"). Highlight ({foreground: ' Orange ', background: ' #ccc '});//Invoke custom highlighting
});

More interested readers of jquery-related content can view the site topics: "jquery common Plug-ins and Usage summary", "jquery Ajax Usage Summary", "jquery table (table) Operation Tips Summary", "jquery drag and drop effects and tips summary", " jquery Extended Skills Summary, jquery Common Classic effects summary, jquery animation and special effects usage summary and jquery selector Usage Summary

I hope this article will help you with the jquery program design.

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.