jquery Source Analysis-03 Structuring jquery objects-tool functions _jquery

Source: Internet
Author: User
Tags anonymous current time extend setinterval xml parser
Author: nuysoft/qq:47214707 email:nuysoft@gmail.com
Statement: This article for the original article, if you want to reprint, please specify the source and retain the original link.
Read and write, the wrong place please tell me, a lot of communication and common progress, this chapter of the PDF and other chapters have finished publishing.
jquery Source Analysis series of directories please check the http://nuysoft.iteye.com/blog/1177451, want to write the system well, now or from the part of my interest, if you have any interested in the module, the proposed priority analysis, you can tell me, Study together.
3.4 Other static tool functions
Copy Code code as follows:

Extended tool functions
Jquery.extend ({
Free JQuery control of $
Many JavaScript libraries use $ as a function or variable name, as well as jQuery.
In jquery, $ is just the alias of jquery, so even if you don't use $, you can guarantee all of the functionality.
If we need to use another JavaScript library outside of JQuery, we can return control to the library by calling $.noconflict ().
By passing the argument true to this method, we can return control of $ and jQuery back to another JavaScript library.
Noconflict:function (deep) {
Handing over the control of $
if (window.$ = = jQuery) {
window.$ = _$;
}
Handing over jquery control.
if (deep && window.jquery = = jQuery) {
Window.jquery = _jquery;
}
return jQuery;
},
Is the DOM ready to be used? Set to True once it occurs.
Isready:false,
A counter to track how many the items to the wait for before
The Ready event fires. #6781
A counter that tracks the number of waits before the Ready event starts
Readywait:1,
Hold (or release) the Ready event
Continue to wait or trigger
Holdready:function (Hold) {
if (hold) {
jquery.readywait++;
} else {
Jquery.ready (TRUE);
}
},
Handle the DOM is ready
Document loaded handle
Ready:function (Wait) {
Either a released hold or a Domready/load event and not yet ready
//
if (wait = = True &&!--jquery.readywait) | | (Wait!== true &&!jquery.isready)) {
Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
Make sure document.body exists
if (!document.body) {
Return settimeout (Jquery.ready, 1);
}
Remember that the DOM is ready
Jquery.isready = true;
If a normal DOM Ready event fired, decrement, and wait if need to be
if (wait!== true &&--jquery.readywait > 0) {
Return
}
If There are functions bound, to execute
Readylist.resolvewith (document, [JQuery]);
Trigger any bound Ready events
if (JQuery.fn.trigger) {
JQuery (document). Trigger ("Ready"). Unbind ("Ready");
}
}
},
Initializing the Readylist event-handler function queue
Compatibility differences between browsing and binding events
Bindready:function () {
if (readylist) {
Return
}
Readylist = jquery._deferred ();
Catch cases where $ (document). Ready () is called
Browser event has already occurred.
if (document.readystate = = "complete") {
Handle it asynchronously to allow scripts the opportunity to delay ready
Return settimeout (Jquery.ready, 1);
}
Mozilla, Opera and WebKit nightlies currently support this event
Compatibility events, by detecting the browser's functionality rather than sniffing the browser
if (Document.addeventlistener) {
Use the handy event callback
Use a faster load complete event
Document.addeventlistener ("domcontentloaded", domcontentloaded, false);
A fallback to window.onload, that'll always work
Registering Window.onload callback functions
Window.addeventlistener ("Load", Jquery.ready, false);
If IE event model is used
else if (document.attachevent) {
Ensure firing before onload,
Maybe late but safe also for IFRAMEs
Be sure to trigger onreadystatechange before onload, it may be slower but safer for iframes
Document.attachevent ("onReadyStateChange", domcontentloaded);
A fallback to window.onload, that'll always work
Registering Window.onload callback functions
Window.attachevent ("onload", Jquery.ready);
If IE and not a frame
Continually check to-if the document is ready
var toplevel = false;
try {
TopLevel = Window.frameelement = = NULL;
catch (e) {}
if (Document.documentElement.doScroll && toplevel) {
Doscrollcheck ();
}
}
},
Test/unit/core.js for details concerning isfunction.
Since version 1.3, DOM methods and functions like alert
Aren ' t supported. They return False on IE (#2968).
Whether the function
Isfunction:function (obj) {
return Jquery.type (obj) = = "function";
},
Whether an array
If the browser has a built-in Array.isarray implementation, use the browser's own implementation,
Otherwise, convert the object to string to see if it is "[Object Array]".
IsArray:Array.isArray | | function (obj) {
return Jquery.type (obj) = = "Array";
},
A crude way of determining if an object is a window
Simple Judgment (judging SetInterval property) whether the Window object
Iswindow:function (obj) {
return obj && typeof obj = = "Object" && "SetInterval" in obj;
},
is the reserved word nan
Isnan:function (obj) {
equals null or not number or call Window.isnan judgment
return obj = = NULL | | !rdigit.test (obj) | | isNaN (obj);
},
Get the type of the object
Type:function (obj) {
Create an object from the core API without needing the new keyword
normal function not
Call the Object.prototype.toString method to generate a string in the format "[Object Xxx]"
class2type["[Object" + name + "]"] = Name.tolowercase ();
return obj = null?
String (obj):
class2type[Tostring.call (obj)] | | "Object";
},
Check to see if obj is a pure object (objects created by "{}" or "New Object")
Console.info ($.isplainobject ({})); True
Console.info ($.isplainobject (')); False
Console.info ($.isplainobject (document.location)); True
Console.info ($.isplainobject (document)); False
Console.info (New Date ()) ($.isplainobject); False
Console.info ($.isplainobject ()); False
Isplainobject Analysis and Reconstruction http://www.jb51.net/article/25047.htm
The understanding of Jquery.isplainobject () http://www.cnblogs.com/phpmix/articles/1733599.html
Isplainobject:function (obj) {
Must is an Object.
Because of IE, we also have to check the presence of the constructor property.
Make sure the DOM nodes and window objects don ' t pass through, as
Must be an object
Because illegal pointer exceptions are thrown in IE8, the constructor property must be checked
DOM nodes and window objects, returning false
Obj does not exist or is not an object type or a DOM node or a Widnow object and returns false directly
Test the following three possible scenarios:
Jquery.type (obj)!== the "object" type is not object, ignoring
Obj.nodetype that DOM nodes are not pure objects
Jquery.iswindow (obj) that Windows is not a pure object
if (!obj | | jquery.type (OBJ)!== "Object" | | obj.nodetype | | jquery.iswindow (obj)) {
return false;
}
Not own constructor property must is Object
Testing constructor Properties
Has a constructor constructor, but not its own property (that is, inherited through prototype),
if (Obj.constructor &&
!hasown.call (obj, "constructor") &&
!hasown.call (Obj.constructor.prototype, "isprototypeof")) {
return false;
}
OWN properties are enumerated firstly, so to speed up,
If is own, the then all properties are own.
var key;
for (key in obj) {}
Key = = undefined and does not exist any attributes that are considered simple pure objects
Hasown.call (obj, key) property key is not empty and the object of the property key itself (that is, not inherited through prototype)
return key = = Undefined | | Hasown.call (obj, key);
},
is empty object
Isemptyobject:function (obj) {
for (var name in obj) {
return false;
}
return true;
},
Throws an exception
Error:function (msg) {
Throw msg;
},
Parsing JSON
Parsejson a string into a JSON object.
We are generally using eval. Parsejson encapsulates this operation, but Eval is treated as a last resort.
The API for JSON serialization and deserialization has been added to the latest JavaScript standards.
If the browser supports this standard, then these two APIs are implemented in native code in the JS engine, and the efficiency is certainly much higher than the eval.
For now, both Chrome and FIREFOX4 support this API.
Parsejson:function (data) {
if (typeof data!== "string" | | |!data) {
return null;
}
Make sure leading/trailing whitespace is removed (IE can ' t handle it)
data = Jquery.trim (data);
Attempt to parse using the native JSON parser
Native JSON API. Deserialization is json.stringify (object)
if (window. JSON && windows. Json.parse) {
return window. Json.parse (data);
}
Make sure the incoming data is actual JSON
Logic borrowed from Http://json.org/json2.js
// ... Check the string legitimacy roughly
if (Rvalidchars.test data.replace (Rvalidescape, "@")
. replace (Rvalidtokens, "]")
. replace (Rvalidbraces, ""))) {
Return (The New Function ("return" + Data)) ();
}
Jquery.error ("Invalid JSON:" + data);
},
Cross-browser XML parsing
(XML & TMP used internally)
Parsing xml across browsers
The Parsexml function is also mainly the standard API and the encapsulation of IE.
Standard APIs are Domparser objects.
And IE uses the ActiveXObject object of Microsoft.XMLDOM.
Parsexml:function (data, XML, TMP) {
if (window. Domparser) {//Standard standard XML Parser
TMP = new Domparser ();
XML = tmp.parsefromstring (data, "text/xml");
else {//IE XML parser
XML = new ActiveXObject ("Microsoft.XMLDOM");
Xml.async = "false";
Xml.loadxml (data);
}
TMP = xml.documentelement;
if (! tmp | |! tmp.nodename | | tmp.nodename = = "ParserError") {
Jquery.error ("Invalid XML:" + data);
}
return XML;
},
No action function
Noop:function () {},
Evaluates a script in a global context
Workarounds based on findings by Jim Driscoll
Http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
The Globaleval function loads a script into the Global Context (window).
Window.execscript can be used in IE.
Other browsers need to use Eval.
Because the entire jquery code is an entire anonymous function, the current context is jquery, and you need to use Globaleval if you want to set it to window.
Globaleval:function (data) {
Data is not empty
if (Data && rnotwhite.test (data)) {
We use execscript on Internet Explorer
We use a anonymous function so this is window
Rather than jQuery in Firefox
(Window.execscript | | function (DATA) {
window["eval"].call (window, data);
}) (data);
}
},
Determine if the node name is the same
Nodename:function (Elem, name) {
Ignore case
return elem.nodename && elem.nodeName.toUpperCase () = = Name.touppercase ();
},
Args is to internal usage only
Traversing an object or array
Each:function (object, callback, args) {
var name, i = 0,
Length = Object.length,
Isobj = length = = Undefined | | Jquery.isfunction (object);
If there is a parameter args, invoke apply, the context is set to the object currently traversed, and the parameters are used args
if (args) {
if (isobj) {
For (name in object) {
if (callback.apply (object[name], args) = = False) {
Break
}
}
} else {
for (; i < length;) {
if (callback.apply (object[i++], args) = = False) {
Break
}
}
}
A Special, fast, case for the most common use of each
Called if there is no parameter args, the call is called, the context is set to the object currently traversed, and the parameter is set to Key/index and value
} else {
if (isobj) {
For (name in object) {
if (Callback.call (object[name, name, object[name]) = = False) {
Break
}
}
} else {
for (; i < length;) {
if (Callback.call (object[i], I, object[i++]) = = False) {
Break
}
}
}
}
return object;
},
Use native String.Trim function wherever possible
Use the local String.Trim method as much as possible, otherwise filter the first space, then filter the trailing spaces
Trim:trim?
function (text) {
return text = null?
"" :
Trim.call (text);
} :
Otherwise use our own trimming functionality
function (text) {
return text = null?
"" :
Text.tostring (). Replace (Trimleft, ""). Replace (TrimRight, "");
},
Results is to internal usage only
Convert pseudo array to array
Makearray:function (array, results) {
var ret = Results | | [];
if (array!= null) {
The window, strings (and functions) also have ' length '
The extra typeof function check is to prevent crashes
In Safari 2 (#3039)
Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
A lot of browser compatibility tests, real egg pain
var type = Jquery.type (array);
Test: There are no length attributes, strings, functions, regular
is not an array, even pseudo arrays are not
if (Array.Length = null
|| Type = = "string"
|| Type = = "function"
|| Type = = "RegExp"
|| Jquery.iswindow (array)) {
Push.call (ret, array);
} else {
$.type ($ (' div '))//Object
Jquery.merge (ret, array);
}
}
return ret;
},
//
Inarray:function (Elem, array) {
Do you have localized Array.prototype.indexOf
if (indexOf) {
Call Array.prototype.indexOf directly
return Indexof.call (array, elem);
}
Iterates through the array to find if there are exactly equal elements and returns the subscript
The trick of looping: storing array.length into the length variable can reduce the scope lookup once
for (var i = 0, length = Array.Length i < length; i++) {
if (array[i] = = Elem) {
return i;
}
}
If 1 is returned, the expression is not in the array
return-1;
},
Merges the array second into the array in the
Merge:function (the second) {
var i = first.length,//
j = 0;
If the length property of the second is a number type, the second is treated as an array
if (typeof second.length = = "Number") {
for (var L = second.length J < L; j + +) {
first[i++] = second[J];
}
} else {
Traverse second to add a undefined value to the
while (Second[j]!== undefined) {
first[i++] = second[j + +];
}
}
Fix the length property of the A, because a may not be a true array
First.length = i;
return A;
},
Filters the array, returns a new array, callback returns True, and if Inv returns false for True,callback, it is preserved.
Grep:function (Elems, callback, inv) {
var ret = [], retVal;
INV =!! Inv
Go through the array, only saving the items
This pass the validator function
Iterate through the array, leaving only the elements callback by the validation function
for (var i = 0, length = elems.length i < length; i++) {
Here callback's argument list is: value, index, consistent with the custom of each
RetVal =!! Callback (elems[i], i);
Whether to select the reverse
if (Inv!== retVal) {
Ret.push (elems[i]);
}
}
return ret;
},
ARG is for internal usage only
Converts an array or object Elems elements/attributes into a new array
Map:function (Elems, Callback, ARG) {
var value, key, ret = [],
i = 0,
Length = Elems.length,
jquery objects are treated as arrays
Detects whether Elems is a (pseudo) array
1. Treat jquery objects as arrays
2. Detects if the length property exists, length equals 0, or whether the first and last elements exist, or Jquery.isarray returns True
IsArray = Elems instanceof jQuery
|| Length!== undefined && typeof length = = "Number"
&& ((length > 0 && elems[0] && elems[length-1]) | | length = = 0 | | Jquery.isarray (elem s));
Is the difference between an array or an object, just the way the traversal is different, no other difference
Go through the "array, translating each of the" items to their
Iterate over the array, call callback for each element, and return the value that is not NULL to the RET
if (IsArray) {
for (; i < length; i++) {
Executes callback, and the arguments are value, index, ARG, in turn
Value = Callback (elems[i], I, ARG);
If NULL is returned, it is ignored (a function with no return value returns undefined)
if (value!= null) {
ret[Ret.length] = value;
}
}
Go through every key on the object,
Iterate over the object, call callback for each attribute, and return the value that is not NULL to the RET
} else {
For (key in Elems) {
Executes callback, and the argument is value, key, arg
Value = Callback (elems[key], key, ARG);
Ditto
if (value!= null) {
ret[Ret.length] = value;
}
}
}
Flatten any nested arrays
Flatten the nested arrays
Concat:
If an item is an array, add its contents to the end.
If the item is not an array, it is added to the end of the array as a single array element.
return ret.concat.apply ([], ret);
},
A Global GUID counter for objects
Guid:1,
Bind a function to a context, optionally partially applying any
Arguments.
Proxy method: Specify context for FN (that is, this)
Jquery.proxy (function, context)
Jquery.proxy (context, name)
Proxy:function (FN, context) {
If the context is a string, the setting is FN,FN to fn[contexts]
That is, the context of the contextual method that sets FN is FN (not by default???) TODO)
if (typeof context = = "string") {
var TMP = fn[context];
context = fn;
fn = tmp;
}
Quick Check to determine if target are callable, in the spec
This throws a typeerror, but we'll just return undefined.
Quickly test whether the FN is callable (that is, a function), in the document description, throw a typeerror,
But this only returns undefined.
if (!jquery.isfunction (FN)) {
return undefined;
}
Simulated bind
var args = Slice.call (arguments, 2),//Remove from the argument list Fn,context
Proxy = function () {
To set context and parameters
Return Fn.apply (the context, Args.concat (Slice.call (arguments));
};
Set the GUID of the unique handler to the same of original handler and so it can be removed
Uniform GUID, allowing proxy to be removed
Proxy.guid = Fn.guid = Fn.guid | | Proxy.guid | | jquery.guid++;
return proxy;
},
Mutifunctional and set values to a collection
The value/s can is optionally by executed if its a function
A multifunction function that reads or sets the property value of a collection, which is executed when the value is a function
Fn:jQuery.fn.css, JQuery.fn.attr, JQuery.fn.prop
Access:function (Elems, key, value, exec, FN, pass) {
var length = Elems.length;
Setting many attributes
If there are multiple properties, the iteration
if (typeof key = = = "Object") {
For (var k in key) {
Jquery.access (Elems, K, Key[k], exec, FN, value);
}
return elems;
}
Setting one attribute
Set only one property
if (value!== undefined) {
Optionally, function values get executed if exec are true
exec =!pass && exec && jquery.isfunction (value);
for (var i = 0; i < length; i++) {
FN (Elems[i], key, exec Value.call (elems[i), I, FN (Elems[i], key)): value, pass;
}
return elems;
}
Getting an attribute
Read properties
return length? FN (Elems[0], key): undefined;
},
Convenient function to get the current time
Now:function () {
Return (new Date ()). GetTime ();
},
Use the Jquery.browser is frowned upon.
More Details:http://docs.jquery.com/utilities/jquery.browser
Do not favor the use of Jquery.browser, recommend the use of Jquery.support
Navigator information for the browser in use
Navigator.useragent a read-only string that declares the value of the user agent header used by the browser for the HTPP request
Uamatch:function (UA) {
UA = Ua.tolowercase ();
Match each browser in turn
var match = rwebkit.exec (UA) | |
Ropera.exec (UA) | |
Rmsie.exec (UA) | |
Ua.indexof ("compatible") < 0 && rmozilla.exec (UA) | |
[];
MATCH[1] | | ""
MATCH[1] is False (empty string, null, undefined, 0, etc.), the default is ""
MATCH[2] | | "0"
MATCH[2] is False (empty string, null, undefined, 0, etc.), the default is "0"
return {Browser:match[1] | | "", Version:match[2] | | " 0 "};
},
Create a new jquery copy, the properties and methods of the replica can be changed, but will not affect the original jquery object
There are two ways to use it:
1. The way to overwrite jquery without destroying the original method
2. Encapsulation, avoid namespace conflicts, can be used to develop jquery plug-ins
It is noteworthy that the jquery.sub () function does not provide true isolation, and that all attributes and methods still point to the original jQuery
If you are using this method to develop Plug-ins, it is recommended that you prioritize the jquery UI widget project
Sub:function () {
function Jquerysub (selector, context) {
Return to New JQuerySub.fn.init (selector, context);
}
Jquery.extend (True, jquerysub, this); Deep copy, copy all of JQuery's properties and methods to Jquerysub
Jquerysub.superclass = this;
Jquerysub.fn = Jquerysub.prototype = This (); //
JQuerySub.fn.constructor = jquerysub;
Jquerysub.sub = this.sub;
JQuerySub.fn.init = function init (selector, context) {
If (context && context instanceof JQuery &&! ( Context instanceof Jquerysub)) {
Context = jquerysub (context);
}
Return JQuery.fn.init.call (this, selector, context, rootjquerysub);
};
JQuerySub.fn.init.prototype = Jquerysub.fn;
var rootjquerysub = jquerysub (document);
return jquerysub;
},
Browser type and version:
$.browser.msie/mozilla/webkit/opera
$.browser.version
The Sniffer browser type Jquery.browser is not recommended, but it examines the browser's functional characteristics Jquery.support
Future Jquery.browser may be moved to a plugin
Browser: {}
});

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.