JavaScript class Library D_javascript tips

Source: Internet
Author: User
Tags wrapper
Because it is a helper class library, in order to be compatible with all other frameworks and class libraries, you extend the object in a wrapper fashion. Class D Library's main content is for JS commonly used built-in objects extensions, such as: string,number,array,date, these extensions to specific business logic, such as the String extension of the trim method, the date extension of the Tostr method, Feature extensions that are commonly used but are not supported by the object itself and are not supported or not fully supported by the Framework class library. At the same time through the packaging of the corresponding packaging we can use the chain method to manipulate the object, and finally each wrapper provides a unboxing (that is, revert to the native object) method. Therefore, the essence of the packaging provided is a boxing, operation, unpacking the process.

Namespaces:
Copy Code code as follows:

var D = {};

Some of the features are as follows:

. String Wrapper
Copy Code code as follows:

(function () {
Wrapping 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 both sides of a string blank
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;
},
Repeating string
Repeat:function (n) {
This.val = Array (n+1). Join (This.val);
return this;
},
String padding on both sides
Padding:function (LEN,DIRE,STR) {
if (This.val.length>=len) return this;
Dire = Dire | | 0; [0 represents the left, 1 represents the right]
str = STR | | " "; Default to a blank character
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 Wrapper

Copy Code code as follows:

(function () {
Packing array
D.arr = function (arr) {
if (!) ( This is instanceof D.arr) return to 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 Packing Device
Copy Code code as follows:

(function () {
Packing number
D.num = function (num) {
if (!) ( This is instanceof D.num) return to 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 Wrapper

Copy Code code as follows:

(function () {
Wrapping Date
D.date = function (date) {
if (!) ( This is instanceof D.date) return to 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":("+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 assume the tasks of DOM operations, implementing the DOM wrapper, as follows:
Copy Code code as follows:

(function () {
2//Packaging DOM
3 D.dom = function (node) {
4 if (!) ( This is instanceof D.dom) return to 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 operation of the current DOM node itself. The "Static Methods" section provides a basic implementation of the DOM selector.

This is the primary version of Class D libraries, an important part of this-the expansion of the built-in objects is currently only a few ways to expand, such as the extension of number, in the web-based financial software, the use of quite a lot of digital operations, some of which are common processing, you can add it add to the numbers wrapper, The benefits are also obvious.

Finally, if you see this article and have enough ideas, I hope you can do what you can to give the wrapper more ways to expand, and some of your ideas may become part of the D mature version.
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.