JavaScript class library D

Source: Internet
Author: User

Because it is a helper class library, in order to be compatible with all other frameworks and class libraries, the package is used to expand the object. The main content of the D Class Library is the extension of common built-in js objects, such as String, Number, Array, and Date. These extensions are biased towards specific business logic, for example, the trim method for String extension and the toStr Method for Date extension are all common function extensions that are not supported by the object itself and are not supported by the framework class library or are not fully supported. At the same time, through the corresponding package, we can operate on the object through the chain method. Finally, each package provides a box removal (that is, restoring to a native object) method. Therefore, the package is actually a process of packing, operating, and unpacking.

Namespace:Copy codeCode: var D = {};

Some functions are as follows:

. String wrapperCopy codeThe Code is as follows: (function (){
// Wrap String
D. str = function (s ){
If (! (This instanceof y. str) return new y. str (s );
This. val = (s! = Undefined )? S. toString ():"";
};
D. str. prototype = {
// Delete the blank spaces on both sides of the string
Trim: function (type ){
Var types = {0: "(^ \ s +) | (\ s + $)", 1: "^ \ s +", 2: "\ s + $ "};
Type = type | 0;
This. val = this. val. replace (new RegExp (types [type], "g "),"");
Return this;
},
// Repeat the string
Repeat: function (n ){
This. val = Array (n + 1). join (this. val );
Return this;
},
// Both sides of the string are white
Padding: function (len, dire, str ){
If (this. val. length> = len) return this;
Dire = dire | 0; // [0 indicates the left, 1 indicates the right]
Str = str | ""; // It is a blank character by default
Var adder = [];
For (var I = 0, l = len-this. val. length; I <l; I ++ ){
Adder. push (str );
}
Adder = adder. join ("");
This. val = dire? (This. val + adder): (adder + this. val );
Return this;
},
Reverse: function (){
This. val = this. val. split (""). reverse (). join ("");
Return this;
},
ByteLen: function (){
Return this. val. replace (/[^ \ x00-\ xff]/g, "--"). length;
},
UnBox: function (){
Return this. val;
}
};
// Alert (D. str ("123"). trim (). repeat (2). padding (10, 0, "x"). reverse (). unBox ());
})();

. Array package

Copy codeThe Code is as follows: (function (){
// Wrap the Array
D. arr = function (arr ){
If (! (This instanceof D. arr) return new D. arr (arr );
This. val = arr | [];
};
D. arr. prototype = {
Each: function (fn ){
For (var I = 0, len = this. val. length; I <len; I ++ ){
If (fn. call (this. val [I]) === false ){
Return this;
}
}
Return this;
},
Map: function (fn ){
Var copy = [];
For (var I = 0, len = this. val. length; I <len; I ++ ){
Copy. push (fn. call (this. val [I]);
}
This. val = copy;
Return this;
},
Filter: function (fn ){
Var copy = [];
For (var I = 0, len = this. val. length; I <len; I ++ ){
Fn. call (this. val [I]) & copy. push (this. val [I]);
}
This. val = copy;
Return this;
},
Remove: function (obj, fn ){
Fn = fn | function (m, n ){
Return m = n;
};
For (var I = 0, len = this. val. length; I <len; I ++ ){
If (fn. call (this. val [I], obj) === true ){
This. val. splice (I, 1 );
}
}
Return this;
},
Unique: function (){
Var o ={}, arr = [];
For (var I = 0, len = this. val. length; I <len; I ++ ){
Var itm = this. val [I];
(! O [itm] | (o [itm]! = Itm) & (arr. push (itm), o [itm] = itm );
}
This. val = arr;
Return this;
},
IndexOf: function (obj, start ){
Var len = this. val. length, start = ~~ Start;
Start <0 & (start + = len );
For (; start <len; start ++ ){
If (this. val [start] === obj) return start;
}
Return-1;
},
LastIndexOf: function (obj, start ){
Var len = this. val. length, start = arguments. length = 2? ~~ Start: len-1;
Start = start <0? (Start + len): (start> = len? (Len-1): start );
For (; start>-1; start --){
If (this. val [start] === obj) return start;
}
Return-1;
},
UnBox: function (){
Return this. val;
}
};
// Alert (D. arr (["123", 123]). unique (). unBox ());
// Alert (D. arr ([1, 2, 3]). map (function (I) {return ++ I ;}). filter (function (I) {return I> 2 ;}). remove (3 ). unBox ());
})();

. Number packageCopy codeThe Code is as follows: (function (){
// Number of packages
D. num = function (num ){
If (! (This instanceof D. num) return new D. num (num );
This. val = Number (num) | 0;
};
D. num. prototype = {
PadZore: function (len ){
Var val = this. val. toString ();
If (val. length> = len) return this;
For (var I = 0, l = len-val.length; I <l; I ++ ){
Val = "0" + val;
}
Return val;
},
FloatRound: function (n ){
N = n | 0;
Var temp = Math. pow (10, n );
This. val = Math. round (this. val * temp)/temp;
Return this;
},
UnBox: function (){
Return this. val;
}
};
// Alert (D. num (3.1235888). floatRound (3). unBox ());
})();

. Date package

Copy codeThe Code is as follows: (function (){
// Package Date
D. date = function (date ){
If (! (This instanceof D. date) return new D. date (date );
If (! (Date instanceof Date )){
Var d = new Date (date );
This. val = (d = "Invalid Date" | d = "NaN ")? New Date (): new Date (date );
} Else {
This. val = date;
}
};
D. date. prototype = {
ToStr: function (tpl ){
Var date = this. val, tpl = tpl | "yyyy-MM-dd hh: mm: ss ";
Var v = [date. getFullYear (), date. getMilliseconds (), date. getMonth () + 1, date. getDate (), date. getHours (), date. getMinutes (), date. getSeconds ()];
Var k = "MM, M, dd, d, hh, h, mm, m, ss, s". split (",");
Var kv = {"yyyy": v [0], "yy": v [0]. toString (). substring (2), "mmss" :( "000" + v [1]). slice (-4), "ms": v [1]};
For (var I = 2; I <v. length; I ++ ){
Kv [k [(I-2) * 2] = ("0" + v [I]). slice (-2 );
Kv [k [(I-2) * 2 + 1] = v [I];
}
For (var k in kv ){
Tpl = tpl. replace (new RegExp (k, "g"), kv [k]);
}
Return tpl;
},
UnBox: function (){
Return this. val;
}
};
// Alert (D. date ("2017-123-12"). toStr ("yyyy-MM-dd hh: mm: ss ms-mmss "));
// Alert (D. date ("2017"). unBox ());
})();

Finally, in order to break away from other framework class libraries, D can also undertake dom operation tasks and implement the Dom wrapper, as shown below:Copy codeThe Code is as follows: (function (){
2 // wrap Dom
3 D. dom = function (node ){
4 if (! (This instanceof D. dom) return new D. dom (node );
5 if (typeof node = "undefined "){
6 node = document. body;
7} else if (typeof node = "string "){
8 node = document. getElementById (node );
9! Node & (node = document. body );
} Else {
! Node. getElementById & (node = document. body );
}
This. val = node;
};
D. dom. prototype = {
Inner: function (value ){
This. val. innerHTML? (Value = value | "", this. val. innerHTML = value): (value = value | 0, this. val. value = value );
Return this;
},
Attr: function (k, v ){
If (typeof k = "object "){
For (var m in k ){
This. val [m] = k [m];
}
} Else {
This. val [k] = v;
}
Return this;
},
Css: function (k, v ){
Var style = this. val. style;
If (typeof k = "object "){
For (var m in k ){
Style [m] = k [m];
}
} Else {
Style [k] = v;
}
Return this;
},
AddClass: function (cls ){
Var clsName = "" + this. val. className + "";
(ClsName. indexOf ("" + cls + "") =-1) & (clsName = (clsName + cls ). replace (/^ \ s + /,""));
This. val. className = clsName;
Return this;
},
RemoveClass: function (cls ){
Var clsName = "" + this. val. className + "";
This. val. className = clsName. replace (new RegExp ("" + cls + "", "g "),""). replace (/(^ \ s +) | (\ s + $ )/,"");
Return this;
},
AddEvent: function (evType, fn ){
Var that = this, typeEvent = this. val ["on" + evType];
If (! TypeEvent ){
(This. val ["on" + evType] = function (){
Var fnQueue = arguments. callee. funcs;
For (var I = 0; I <fnQueue. length; I ++ ){
FnQueue [I]. call (that. val );
}
}). Funcs = [fn];
} Else {
TypeEvent. funcs. push (fn );
}
Return this;
},
DelEvent: function (evType, fn ){
If (fn = undefined ){
This. val ["on" + evType] = null;
} Else {
Var fnQueue = this. val ["on" + evType]. funcs;
For (var I = fnQueue. length-1; I>-1; I --){
If (fnQueue [I] === fn ){
FnQueue. splice (I, 1 );
Break;
}
}
FnQueue. length = 0 & (this. val ["on" + evType] = null );
}
Return this;
},
UnBox: function (){
Return this. val;
}
};
// Static method
Var _ = D. dom;
_. $ = Function (id ){
Return typeof id = "string "? Document. getElementById (id): id;
};
_. $ = Function (tag, box ){
Return (box === undefined? Document: box). getElementsByTagName (tag );
};
_. $ Cls = function (cls, tag, node ){
Node = node === undefined? Document: node;
Cls = cls. replace (/(\.) | (^ \ s +) | (\ s + $)/g ,"");
If (node. getElementsByClassName) return node. getElementsByClassName (cls );
Tag = tag === undefined? "*": Tag;
Var filter = [], nodes = (tag = "*" & node. all )? Node. all: node. getElementsByTagName (tag );
For (var I = 0, j = nodes. length; I <j; I ++ ){
Nodes [I]. nodeType = 1 & ("" + nodes [I]. className + ""). indexOf ("" + cls + "")! =-1) & filter. push (nodes [I]);
}
Return filter;
};
// Static method end
Alert (D. dom. $ cls (". abc"). length );
})();

The instance object of the Dom wrapper is responsible for the operations of the current dom node. The static method provides the basic implementation of the dom selector.

The above is the primary version of the D class library, an important part of which-there are currently only a small Number of extension methods for built-in objects, such as Number extension, in the web-based financial software, A considerable Number of numeric operations are used, some of which are commonly used for processing. You can add them to the Number package. The benefits are also obvious.

Finally, if you have read this article and have enough ideas, I hope you can do your best to give the package more method extensions, some of your ideas may become part of the mature version of D.

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.