jquery Plugin Production Example Tutorial _jquery

Source: Internet
Author: User
Tags anonymous extend wrapper

The types of jquery plug-ins

1. jquery method

A large portion of the jquery plug-ins are of this type, as they encapsulate the object methods and manipulate them in the jquery selector to get the jquery object, giving the jquery a powerful selector advantage.

2. Global Function method

A custom function function can be attached independently to the jquery namespace to be used as a common function in the jquery scope.
However, global functions are not bound to jquery objects and cannot be invoked on the jquery object that the selector obtains. It needs to be referenced by Jquery.fn () or $.fn ().

3. Selector method

Consider customizing the selector if you feel that the selector provided by jquery is not enough or inconvenient.

Second, the jquery plug-in mechanism

1. Jquery.extend () method

This method can create global functions or selectors.

The so-called global function, the method of the JQuery object, is actually a function located inside the jquery namespace, which is called utility functions, which have a common feature, that is, not manipulating DOM elements directly, but manipulating JavaScript's non element objects. or perform other non-object specific operations, such as the each () and noconflict () functions of jquery.

For example, create two common functions on the jquery namespace:


Jquery.extend ({ 
min:function (a,b) {return 
a<b?a:b; 
}, 
max:function (a,b) {return 
a<b?b: A; 
} 
}) 
$ (function () { 
$ ("input"). Click (function () { 
var a = prompt ("Please enter a number:"); 
var B = Prompt ("Enter a second number:"); 
var c = jquery.min (a,b); 
var d = Jquery.max (a,b); 
Alert ("Maximum is: + D +" \ n Minimum value is: "+ C); 
}); 
} 
<input type= "button" value= "jquery extended test"/>

Jquery.extend ({ 
min:function (a,b) {return 
a<b?a:b; 
}, 
max:function (a,b) {return 
a <b?b:a; 
} 
}) 
$ (function () { 
$ ("input"). Click (function () { 
var a = prompt ("Please enter a number:"); 
var B = Prompt ("Enter a second number:"); 
var c = jquery.min (a,b); 
var d = Jquery.max (a,b); 
Alert ("Maximum is: + D +" \ n Minimum value is: "+ C); 
}); 
} 
<input type= "button" value= "jquery extended test"/>

In addition to creating Plug-ins, the Jquery.extend () method can be used to extend the jquery object.

For example, the call to the Jquery.extend () method merges object A and object B into a new object and returns the merged object to assign it to the variable C:

var a = {name: "AAA", pass:777}; 
var b = {name: "BBB", pass:888,age:9}; 
var c = jquery.extend (a,b); 
$ (function () {for 
(var name in c) { 
$ ("div"). HTML ($ ("div"). html () + "<br/>" + name + ":" + C[name]); 
} 
})


If you want to add a function to the jquery namespace, just make the new function a property of the jquery object. The JQuery object name can also be abbreviated to $,JQUERY.SMALLUV==$.SMALLUV.

For example, create a jquery global function:

Jquery.smalluv = { 
min:function (a,b) {return 
a<b?a:b; 
}, 
max:function (a,b) {return 
a <b?b:a; 
} 
} 
$ (function () { 
$ ("input"). Click (function () { 
var a = prompt ("Please enter a number:"); 
var B = Prompt ("Enter a second number:"); 
var c = jQuery.smalluv.min (a,b); 
var d = JQuery.smalluv.max (a,b); 
Alert ("Maximum is: + D +" \ n Minimum value is: "+ C); 
}); 
}


2. JQuery.fn.extend () method

This method can create a JQuery object method.

One of the simplest examples of jquery object methods:

JQuery.fn.test = function () { 
alert ("jquery object Method"); 
} 
$ (function () { 
$ ("div"). Click (function () { 
$ (this). Test (); 
}); 
}


Third, Preliminary summary

In the jquery anonymous function, the Jquery.extend () method is used to create the jquery plugin
In the jquery anonymous function, the jquery plug-in is created using the object. property = function

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

Iv. the preparation of examples

Writing a

Plug-in body:

(Function ($, window) {//initial state defines var _odialogcollections = {}; The plug-in defines $.fn.
      Mndialog = function (_aoconfig) {//default parameter, can be overridden by var defaults = {//String SId: "",//num
      nwidth:400,//Bollean Bdisplayheader:true,//Object ocontenthtml: "",//function
 
    Fclosecallback:null};
 
    var _oself = this, $this = $ (this);
 
    Plug-in configuration This.oconfig = $.extend (defaults, _aoconfig); initializer var _init = function () {if (_odialogcollections) {//For initialized processing///If a bullet box already exists at this time, remove
      Drop and add a new frame}//Initialize pop-up data _initdata ();
      Event binding _loadevent ();      
    Load content _loadcontent ();
    }//Private functions var _initdata = function () {};
    var _loadevent = function () {}; var _loadcontent = function () {//content (character and function two, characters are static templates, functions are assembled after asynchronous request template, will delay, so special processing) if ($.isfunction _oself.oconf ig.ocontenthtml)) {_oself.oconfig.ocontentHtml.call (_oself, function (ocallbackhtml) {//facilitates the transfer of parameter functions to come in and execute _oself.html (ocallbackhtml); A callback function executes _oself.oconfig.floadedcallback && _oself.oconfig.floadedcallback.call (_oself, _oself._oconta
        iner$);
      });
        else if ($.type (_oself.oconfig.ocontenthtml) = = "string") {_oself.html (_oself.oconfig.ocontenthtml);
      _oself.oconfig.floadedcallback && _oself.oconfig.floadedcallback.call (_oself, _oself._ocontainer$); } else {Console.log ("pop-up") is not in the right format, should be a function or string.
      ");
 
    }
    };
 
    Internal use parameter var _oeventalias = {click: ' D_ck ', DblClick: ' D_dbl '};
    Provides external functions this.close = function () {_close ();
 
    }//Start plugin _init ();    
  Chained call return-this;
  };
 Plugin end}) (JQuery, window);

Call

var Mndialog = $ ("#header"). Mndialog ({
  sId: "#footer",    //override default value
  fclosecallback:dialog,//callback function
  Ocontenthtml:function (_ Aocallback) {
      _aocallback (_oeditgrpdlgview.el);
    }
  }
);
Call the supplied function
mndialog.close;
Function dialog () {
 
}

Comments

1. Self-Invoke anonymous function

(Function ($, window) {
 //jquery Code
}) (jquery, window);

Usefulness: By defining an anonymous function, a "private" namespace is created, and the variables and methods of that namespace do not break the global namespace. This is very useful is also a JS framework must support the functionality of jquery is applied to thousands of JavaScript programs, you must ensure that the variables created by jquery cannot conflict with the variables used to import his program.

2. Why do anonymous functions pass in Windows

By passing in the window variable, the window is made local by a global variable, and when Windows is accessed in the jquery code block, the scope chain is not required to be rolled back to the top-level scope, allowing faster access to Windows; That's not the point, and more importantly, Passing windows as a parameter can be optimized while compressing the code to see Jquery.min.js:

(function (a,b) {}) (JQuery, window); jquery is optimized for a, window is optimized for B

3. Global variable This definition

var _oself = this,
$this = $ (this);

Allows you to use this in a plug-in's function to point to the plug-in

4. Plug-in configuration

This.oconfig = $.extend (defaults, _aoconfig);

Set the default parameters, and you can override the default values by passing in parameters when the plug-in is defined

5. Initialization function

A generic plug-in will have an INIT initialization function and initialize it at the end of the plug-in.

6. Private functions, public functions

Private functions: Used in plug-ins, function names are identified with "_" as Prefix

Common functions: Can be used outside the plug-in, the function name uses "this." As a prefix identifier, as a method of the plug-in for external use

7. Return this

Finally, the jquery object is returned to facilitate the chain operation of jquery

Writing two

Main structure

(function ($) {
  $.fn.addrinput = function (_aooptions) {
    var _oself = this;
    _oself.sversion = ' version-1.0.0 ';
    _oself.oconfig = {
      ninputlimitnum:9
    };
    Plug-in configuration
    $.extend (_oself.oconfig, _aooptions);
 
    Call this object's method, passing this
    $.fn.addrinput._initui.call (_oself, event);
    $.fn.addrinput._initevents.call (_oself);
 
    Provides external functions
    This.close = function () {
      _close ();
    }
 
    Returns the JQuery object, easy to jquery chain operation return  
    _oself          
  }
  $.fn.addrinput._initui = function (event) {
    var _oself = this,
      _otarget = $ (event.currenttarget);
  }
  $.fn.addrinput._initevents = function () {}
}) (Window.jquery);

Comments

1. Beautiful

The plug-in method is written externally and is called by the way the plugin body passes this

2. Define the plug-in version number

But it's still not used here.

3. About Call

The first argument here is to pass this, and the following are all parameters

Grammar:

Call ([thisobj[,arg1[, arg2[, [,. argn]]]]
Definition: Invokes one method of an object, replacing the current object with another object.

Description: The call method can be used to invoke a method instead of another object. The call method can change the object context of a function from the initial context to the new object specified by Thisobj. If the thisobj parameter is not supplied, the Global object is used as a thisobj.

4. About "This"

In the plug-in's method, it may be useful to point to this for the plug-in, and to point to this event trigger, so the event triggers this to be obtained by using event: Event.cuerrnttarget

Event.currenttarget: Points to the element that the event is bound to, and finds the element up in the event bubbling Way
Event.target: Always point to the element at which the event occurred
Such as:

HTML code

<div id= "wrapper" > 
  <a href= "#" id= "inner" >click here!</a> 
</div>

JS Code

$ (' #wrapper '). Click (function (e) { 
  console.log (' #wrapper '); 
  Console.log (e.currenttarget); 
  Console.log (E.target); 
}); 
$ (' #inner '). Click (function (e) { 
  console.log (' #inner '); 
  Console.log (e.currenttarget); 
  Console.log (E.target); 
});

Result output

#inner
<a href= "#" id= "inner" > click here! </a>
<a href= "#" id= "inner" > click here! </a& gt;
#wrapper
<div id= "wrapper" > <a href= "#" id= "inner" > click here! </a> </div>
<a href= "#" id= "inner" > click here! </a>

Writing three (native writing)

Main structure

var Membercard = function (_aooption) {
  //configuration (the default is to be passed in from the outside)
  _aooption | | (_aooption = {});
  Initialize function
  _init (this);
}
 
var _init = function (_aoself) {
  //Functions Execution
  _initdata (_aoself);
  Calling the object's private method
  _aoself._timedhide ();
}
 
var _initdata = function (_aoself) {}
 
//Private method
Membercard.prototype._timedhide = function (_aooptions) {
  V Ar _oself = this;
  Cleartimeout (This.ihidetimer);  
  Use the Underscore.js extend method to implement the attribute overlay
  var odefault = Extend ({nhidetime:300}, _aooptions);
  _oself.ihidetimer = settimeout (function () {
    ///() common method of calling object
    _oself.hide ();
  }, Odefault.nhidetime);    
}
 
//Public methods
MemberCard.prototype.hide = function (_aooptions) {}

Use

var ocolleaguecard = new Membercard ({nhidetime:200});
Ocolleaguecard.hide ();

Comments:

1. About attribute overrides (Object deep copy)

The realization method of native function

function GetType (o) {return
  (_t = typeof (o)) = = "Object"? O==null && "Null" | | Object.prototype.toString.call (o). Slice (8,-1): _t). toLowerCase ();
function Extend (Destination,source) {for
  (Var p in source) {
    if (GetType (source[p)) = = "Array" | | GetType (source[p]) = = "Object") {
      destination[p]=gettype (source[p]) = = "Array"? []:{};
      Arguments.callee (Destination[p],source[p]);
    else{
      destination[p]=source[p];}}

Demo

var test={a: "SS", B:[1,2,3],c:{d: "CSS", E: "CDD"}};
var test1={};
Extend (test1,test);
test1.b[0]= "Change"; Change the No. 0 array element alert (Test.b[0] of the B Property object of the Test1
);//Do not affect test, return 1
alert (test1.b[0]);//return changes

The implementation method based on jquery:

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.

Demo

var options = {id: "NAV", Class: "Header"}
var config = $.extend ({id: "Navi"}, Options);//config={id: "Nav", Class: " Header "}

2. About this

All methods of this object point to this object, so there is no need to reassign

Writing Four

Main structure

function Editorutil () {
  this._editorcontent = $ (' #editor_content ');
  THIS._PICBTN = $ (' #project_pic ');
  This.iebookmark = null;
}
Editorutil.prototype = {
  Consturctor:editorutil,
 
  notebookmark:function () {
  },
  htmlreplace: function (text) {
    if (typeof text = = ' string ') {return
      text.replace (/[<>) &]/g, function (match, p OS, originaltext {
        switch (match) {case
          ' < ': return
            ' < ';
          Case ' > ': Return
            ' > ';
          Case ' & ': Return
            ' & ';
          Case ' "': Return
            '" ';
        }} "
      ;
    }
    return ';
  },
  init:function () {
    this._membtn.bind (' click ', Function (event) {
      $ (". Error_content "). Hide ();
      return false;
    };
 
Initializes the Rich Text editor
var editor = new Editorutil ();
Editor.init ();

Summarize

Writing four and writing three are actually similar, but have you seen the difference?

There are two ways to add a method to an object using a prototype chain:

Writing three:

Membercard.prototype._timedhide
MemberCard.prototype.hide

Writing four:

Editorutil.prototype = {
  Consturctor:editorutil,
  notebookmark:function () {},  
  htmlreplace:function () {}
}

A closer look at writing four ways to add a method to the Editorutil object by using the "Object Direct Quantity", and the difference between the written three is to write four that would result in a Consturctor property change.

Constructor property: Always point to the constructor that created the current object

Each function has a default property prototype, and this prototype constructor the default point to this function. As shown in the following example:

function person (name) {this.name = name; 
}; 
Person.prototype.getName = function () {return this.name; 
}; 

var p = new Person ("Zhangsan"); Console.log (P.constructor = = person); True Console.log (Person.prototype.constructor = = person); True//Merge the two lines of code to get the following result Console.log (P.constructor.prototype.constructor = = person); 
true function person (name) {this.name = name; 
}; 
Person.prototype.getName = function () {return this.name; 
}; 
 
var p = new Person ("Zhangsan"); Console.log (P.constructor = = person); True Console.log (Person.prototype.constructor = = person); True//Merge the two lines of code to get the following result Console.log (P.constructor.prototype.constructor = = person);  True when we redefine the prototype of a function (note: The difference between this and the previous example is not a modification but a overwrite), the behavior of the constructor property is a bit odd, as follows: function person (name) {this.name = 
Name 
}; 
  Person.prototype = {Getname:function () {return this.name; 
} 
}; 
var p = new Person ("Zhangsan"); Console.log (P.constructor = = person); False Console.log(Person.prototype.constructor = = person); False Console.log (P.constructor.prototype.constructor = = person);

 False

Why, then?

It turns out that overwriting person.prototype is equivalent to doing the following code:

Person.prototype = new Object ({ 
  getname:function () {return 
    this.name; 
  } 
});

Person.prototype = new Object ({ 
  getname:function () {return 
    this.name; 
  } 
});


And the constructor property always points to the constructor that created itself, so Person.prototype.constructor = = Object at this point, that is:

function person (name) { 
  this.name = name; 
}; 
Person.prototype = { 
  getname:function () {return 
    this.name; 
  } 
}; 
var p = new Person ("Zhangsan"); 
Console.log (P.constructor = = = Object); True 
console.log (Person.prototype.constructor = = = Object);//True 
Console.log ( P.constructor.prototype.constructor = = = Object); True

function Person (name) { 
  this.name = name; 
}; 
Person.prototype = { 
  getname:function () {return 
    this.name; 
  } 
}; 
var p = new Person ("Zhangsan"); 
Console.log (P.constructor = = = Object); True 
console.log (Person.prototype.constructor = = = Object);//True 
Console.log ( P.constructor.prototype.constructor = = = Object); True


How to fix this problem? The method is also very simple, the Person.prototype.constructor can be overwritten again:

function person (name) { 
  this.name = name; 
}; 
Person.prototype = new Object ({ 
  getname:function () {return 
    this.name; 
  } 
}); 
Person.prototype.constructor = person; 
var p = new Person ("Zhangsan"); 
Console.log (P.constructor = = person); True 
console.log (Person.prototype.constructor = = person);//True 
Console.log ( P.constructor.prototype.constructor = = person); True

function Person (name) { 
  this.name = name; 
}; 
Person.prototype = new Object ({ 
  getname:function () {return 
    this.name; 
  } 
}); 
Person.prototype.constructor = person; 
var p = new Person ("Zhangsan"); 
Console.log (P.constructor = = person); True 
console.log (Person.prototype.constructor = = person);//True 
Console.log ( P.constructor.prototype.constructor = = person); True


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.