Examples of jQuery plug-ins and jquery plug-ins

Source: Internet
Author: User

Examples of jQuery plug-ins and jquery plug-ins

I. jQuery plug-in type

1. jQuery Method

A large part of jQuery plug-ins are of this type. Because these plug-ins encapsulate object methods, they operate when the jQuery selector obtains jQuery objects, so as to take advantage of jQuery's powerful selector.

2. Global Function Method

You can independently attach a user-defined function to the jQuery namespace and use it as a public function under the jQuery scope.
However, the global function is not bound to the jQuery object, so it cannot be called on the jQuery object obtained by the selector. It must be referenced using jQuery. fn () or $. fn.

3. selector Method

If you think that the selector provided by jQuery is insufficient or inconvenient, you can consider customizing the selector.

Ii. jQuery plug-in mechanism

1. jQuery. extend () method

This method creates a global function or selector.

The so-called global function is the jQuery object method. It is actually a function located inside the jQuery namespace. Some people call this type of function as a utility function. These functions share a common feature, instead of operating DOM elements directly, you can operate non-element objects in Javascript, or execute other non-object-specific operations, such as jQuery's each () function and noConflict () function.

For example, create two public functions in 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 ("enter a number:"); var B = prompt ("enter another number:"); var c = jQuery. min (a, B); var d = jQuery. max (a, B); alert ("maximum value:" + d + "\ n minimum value:" + c );});})
<Input type = "button" value = "jQuery Extension 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 ("enter a number:"); var B = prompt ("enter another number:"); var c = jQuery. min (a, B); var d = jQuery. max (a, B); alert ("maximum value:" + d + "\ n minimum value:" + c );});})
<Input type = "button" value = "jQuery Extension Test"/>

In addition to creating plug-ins, The jQuery. extend () method can also be used to expand jQuery objects.

For example, call jQuery. extend () to merge object a and object B into a new object, and return the merged object to assign it to 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]); } })


To add a function to the jQuery namespace, you only need to define the new function as an attribute of the jQuery object. The jQuery object name can also be abbreviated as $, jQuery. smalluv = $. smalluv.

For example, to 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 ("enter a number:"); var B = prompt ("enter another number:"); var c = jQuery. smalluv. min (a, B); var d = jQuery. smalluv. max (a, B); alert ("maximum value:" + d + "\ n minimum value:" + c );});})


2. jQuery. fn. extend () method

This method allows you to create jQuery object methods.

Here is an example of the simplest jQuery object method:

JQuery. fn. test = function () {alert ("jQuery object method") ;}$ (function () {$ ("div "). click (function () {$ (this ). test ();});})


Iii. Preliminary Summary

In the jQuery anonymous function, jQuery. extend (); method is used to create the jQuery plug-in.
In jQuery anonymous functions, the jQuery plug-in is created using the object. Property = function method.

<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> 

4. Compile an instance

Method 1

Agent body:

(Function ($, window) {// initial state definition var _ oDialogCollections ={}; // plug-in definition $. fn. MNDialog = function (_ aoConfig) {// default parameter. You can override var defaults = {// string sId: "", // num nWidth: 400, // bollean bDisplayHeader: true, // object oContentHtml: "", // function fCloseCallback: null}; var _ oSelf = this, $ this = $ (this); // configure this for the plug-in. oConfig = $. extend (defaults, _ aoConfig); // initialization function var _ init = function () {If (_ oDialogCollections) {// initialization processing // if a dialog box already exists, remove and add a new pop-up box} // initialize the pop-up box data _ initData (); // event binding _ loadEvent (); // load content _ loadContent ();} // Private function var _ initData = function () {}; var _ loadEvent = function () {}; var _ loadContent = function () {// content (two types: character and function. The character is a static template, and the function is a template assembled after an asynchronous request, which will be delayed, so special processing) if ($. isFunction (_ oSelf. oConfig. oContentHtml) {_ oSelf. oConfig. oContentHtml. call (_ oSelf, function (OCallbackHtml) {// it is convenient to pass in the Parameter Function and execute _oSelf.html (oCallbackHtml); // if there is a callback function, execute _ oSelf. oConfig. fLoadedCallback & _ oSelf. oConfig. fLoadedCallback. call (_ oSelf, _ oSelf. _ oContainer $) ;}) ;}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 ("the content in the pop-up box is incorrectly formatted. It should be a function or string. ") ;}}; // Internal use parameter var _ oEventAlias = {click: 'd _ ck ', dblclick: 'd _ dbl'}; // provides the external function this. close = function () {_ close () ;}// start INS _ init (); // chained call return this ;}; //} }) (jQuery, window );

Call

Var MNDialog =$ ("# header "). MNDialog ({sId: "# footer", // overwrite the default fCloseCallback: dialog, // callback function oContentHtml: function (_ aoCallback) {_ aoCallback (_ oEditGrpDlgView. el) ;}}); // call the provided function MNDialog. close; function dialog (){}

Comments

1. Self-called anonymous Functions

(function($, window) { // jquery code})(jQuery, window);

Usage: Creates a "private" namespace by defining an anonymous function. The variables and methods of the namespace do not destroy the global namespace. This is very useful and a function that must be supported by the JS framework. jQuery is applied to thousands of JavaScript programs, make sure that the variable created by jQuery cannot conflict with the variable used by the program to be imported.

2. Why does an anonymous function pass in a window?

Pass in the window variable so that the window is changed from a global variable to a local variable. When you access the window in the jQuery code block, you do not need to roll back the scope chain to the top-level scope, so that you can access the window more quickly; this is not the key. More importantly, you can use window as a parameter and optimize it when compressing the code. Let's take a look at jquery. min. js:

(Function (a, B) {}) (jQuery, window); // jQuery is optimized to a, window is optimized to B

3. global variable this definition

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

This allows you to use

4. Plug-in configuration

this.oConfig = $.extend(defaults, _aoConfig);

Set the default parameters. You can also overwrite the default values when defining the plug-in.

5. initialize the Function

The General Plug-in will have the init initialization function and initialize it at the end of the plug-in.

6. Private and Public Functions

Private function: Used in the plug-in, and the function name uses "_" as the prefix.

Common functions: they can be used outside the plug-in. The function name uses "this." As the prefix identifier and is used as a method of the plug-in for external use.

7. return this

Returns the jQuery object to facilitate jQuery's chained operations.

Statement 2

Body 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 the method of this object and pass this $. fn. addrInput. _ initUI. call (_ oSelf, event); $. fn. addrInput. _ initEvents. call (_ oSelf); // provides the external function this. close = function () {_ close () ;}// return the jQuery object, which facilitates the 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 called by passing this in the plug-in Body

2. Define the plug-in version number

However, it is still useless here.

3. call

The first parameter here is to pass this, followed by all parameters

Syntax:

Call ([thisObj [, arg1 [, arg2 [, [,. argN])
Definition: call a method of an object to replace the current object with another object.

Note: The call method can be used to call 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 provided, the Global object is used as thisObj.

4. About "this"

In the plug-in method, it may be useful to point to the plug-in this, and to the event-triggered this, so the event-triggered this is obtained using the event. cuerrntTarget

Event. currentTarget: point to the element bound to the event. Locate the element in the event bubble mode.
Event.tar get: always point to the element when an event occurs.
For example:

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>​#wrapper<div id=​"wrapper">​<a href=​"#" id=​"inner">​click here!​</a>​</div>​<a href=​"#" id=​"inner">​click here!​</a>​

Writing Method 3 (native writing)

Body Structure

Var MemberCard = function (_ aoOption) {// configuration (imported from outside by default) _ aoOption | (_ aoOption = {}); // initialize function _ init (this);} var _ init = function (_ aoSelf) {// function execution _ initData (_ aoSelf ); // call the object's private method _ aoSelf. _ timedHide ();} var _ initData = function (_ aoSelf) {}// private method MemberCard. prototype. _ timedHide = function (_ aoOptions) {var _ oSelf = this; clearTimeout (this. iHideTimer); // use underscore. js extend method to implement attribute override var oDefault = extend ({nHideTime: 300}, _ aoOptions); _ oSelf. iHideTimer = setTimeout (function () {// call the object's common method _ oSelf. hide () ;}, oDefault. nHideTime);} // public method MemberCard. prototype. hide = function (_ aoOptions ){}

Use

var oColleagueCard = new MemberCard({ nHideTime: 200 });oColleagueCard.hide();

Comments:

1. About property overwrite (Object deep copy)

Native function implementation method

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 0th array element alert (test. B [0]); // test is not affected. 1 alert (test1. B [0]) is returned. // change is returned.

JQuery-based implementation:

jQuery.extend([deep], target, object1, [objectN]);

Use one or more other objects to expand an object and return the extended object.

If no target is specified, the jQuery namespace itself is extended. This helps the plug-in author Add a new method for jQuery. If the first parameter is set to true, jQuery returns a deep copy to recursively copy any objects found. Otherwise, the copy will share the structure with the original object. Undefined attributes will not be copied, but attributes inherited from the object's prototype will be copied.

Demo:

var options = {id: "nav", class: "header"}var config = $.extend({id: "navi"}, options); //config={id: "nav", class: "header"}

2. About this

This of all methods of this object point to this object, so you do not need to re-specify

Statement 4

Body 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, pos, 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 ;}};/// initialize the Rich Text editor var editor = new EditorUtil (); editor. init ();

Summary

Writing Method 4 is similar to writing method 3, but do you know the difference?

Both methods use the prototype chain to add objects:

Statement 3:

MemberCard.prototype._timedHideMemberCard.prototype.hide

Statement 4:

EditorUtil.prototype = {  consturctor: EditorUtil,  noteBookmark: function(){},    htmlReplace: function(){}}

Let's take a closer look at the way to add an EditorUtil object using the method of "Object Direct Volume". The difference with method 3 is that writing method 4 will change the consturctor attribute.

Constructor attribute: always points to the constructor that creates the current object.

Each function has a default prototype attribute, and the constructor of this prototype points to this function by default. For 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 above two lines of code to obtain the following result console. log (p. constructor. prototype. constructor = Person); // truefunction 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 above two lines of code to obtain the following result console. log (p. constructor. prototype. constructor = Person); // true when we re-define the prototype of the function (Note: The difference between this parameter and the previous example is not modified but overwritten ), the behavior of the constructor attribute is a bit strange, 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); // false console. log (Person. prototype. constructor = Person); // false console. log (p. constructor. prototype. constructor === Person); // false

Why?

It turns out that when people. prototype is overwritten, it is equivalent to performing the following code operations:

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


The constructor attribute always points to the creation of its own constructor, so at this time Person. prototype. constructor = Object, 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); // truefunction 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 can we fix this problem? The method is also very simple. Just overwrite Person. prototype. constructor 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); // truefunction 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


Related Article

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.