-
Notifications
You must be signed in to change notification settings - Fork 535
/
mass_merge.js
6022 lines (5806 loc) · 258 KB
/
mass_merge.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
!function(global, DOC) {
var $$ = global.$; //保存已有同名变量
var rmakeid = /(#.+|\W)/g; //用于处理掉href中的hash与所有特殊符号,生成长命名空间
var NsKey = DOC.URL.replace(rmakeid, ""); //长命名空间(字符串)
var NsVal = global[NsKey]; //长命名空间(mass对象)
var W3C = DOC.dispatchEvent; //IE9开始支持W3C的事件模型与getComputedStyle取样式值
var html = DOC.documentElement; //HTML元素
var head = DOC.head || DOC.getElementsByTagName("head")[0]; //HEAD元素
var loadings = []; //正在加载中的模块列表
var factorys = []; //储存需要绑定ID与factory对应关系的模块(标准浏览器下,先parse的script节点会先onload)
var mass = 1; //当前框架的版本号
var postfix = ""; //用于强制别名
var all = "mass,lang,class,flow,data,support,query,node,attr,css,event,ajax,fx";
var moduleClass = "mass" + (new Date - 0);
var hasOwn = Object.prototype.hasOwnProperty;
var class2type = {
"[object HTMLDocument]": "Document",
"[object HTMLCollection]": "NodeList",
"[object StaticNodeList]": "NodeList",
"[object DOMWindow]": "Window",
"[object global]": "Window",
"null": "Null",
"NaN": "NaN",
"undefined": "Undefined"
};
var serialize = class2type.toString,
basepath, kernel;
function $(expr, context) { //新版本的基石
if (typeof expr === "function" && expr.call) { //注意在safari下,typeof nodeList的类型为function,因此必须使用$.type
return $.require(all + ",ready", expr);
}
if (!$.fn)
$.error("必须加载node模块");
return new $.fn.init(expr, context);
}
//多版本共存
if (typeof NsVal !== "function") {
NsVal = $; //公用命名空间对象
NsVal.uuid = 1;
}
if (NsVal.mass !== mass) {
NsVal[mass] = $; //保存当前版本的命名空间对象到公用命名空间对象上
if (NsVal.mass || ($$ && $$.mass == null)) {
postfix = (mass + "").replace(/\D/g, ""); //是否强制使用多库共存
}
} else {
return;
}
function mix(receiver, supplier) {
var args = [].slice.call(arguments),
i = 1,
key, //如果最后参数是布尔,判定是否覆写同名属性
ride = typeof args[args.length - 1] === "boolean" ? args.pop() : true;
if (args.length === 1) { //处理$.mix(hash)的情形
receiver = !this.window ? this : {};
i = 0;
}
while ((supplier = args[i++])) {
for (key in supplier) { //允许对象糅杂,用户保证都是对象
if (hasOwn.call(supplier, key) && (ride || !(key in receiver))) {
receiver[key] = supplier[key];
}
}
}
return receiver;
}
//为此版本的命名空间对象添加成员
mix($, {
html: html,
head: head,
mix: mix,
rword: /[^, ]+/g,
rmapper: /(\w+)_(\w+)/g,
mass: mass,
hasOwn: function(obj, key) {
return hasOwn.call(obj, key);
},
//大家都爱用类库的名字储存版本号,我也跟风了
"@bind": W3C ? "addEventListener" : "attachEvent",
slice: W3C ? function(nodes, start, end) {
return factorys.slice.call(nodes, start, end);
} : function(nodes, start, end) {
var ret = [],
n = nodes.length;
if (end === void 0 || typeof end === "number" && isFinite(end)) {
start = parseInt(start, 10) || 0;
end = end == void 0 ? n : parseInt(end, 10);
if (start < 0) {
start += n;
}
if (end > n) {
end = n;
}
if (end < 0) {
end += n;
}
for (var i = start; i < end; ++i) {
ret[i - start] = nodes[i];
}
}
return ret;
},
getUid: W3C ? function(obj) { //IE9+,标准浏览器
return obj.uniqueNumber || (obj.uniqueNumber = NsVal.uuid++);
} : function(obj) {
if (obj.nodeType !== 1) { //如果是普通对象,文档对象,window对象
return obj.uniqueNumber || (obj.uniqueNumber = NsVal.uuid++);
} //注:旧式IE的XML元素不能通过el.xxx = yyy 设置自定义属性
var uid = obj.getAttribute("uniqueNumber");
if (!uid) {
uid = NsVal.uuid++;
obj.setAttribute("uniqueNumber", uid);
}
return +uid; //确保返回数字
},
bind: W3C ? function(el, type, fn, phase) {
el.addEventListener(type, fn, !!phase);
return fn;
} : function(el, type, fn) {
el.attachEvent && el.attachEvent("on" + type, fn);
return fn;
},
unbind: W3C ? function(el, type, fn, phase) {
el.removeEventListener(type, fn || $.noop, !!phase);
} : function(el, type, fn) {
if (el.detachEvent) {
el.detachEvent("on" + type, fn || $.noop);
}
},
type: function(obj, str) {
var result = class2type[(obj == null || obj !== obj) ? obj : serialize.call(obj)] || obj.nodeName || "#";
if (result.charAt(0) === "#") { //兼容旧式浏览器与处理个别情况,如window.opera
//利用IE678 window == document为true,document == window竟然为false的神奇特性
if (obj == obj.document && obj.document != obj) {
result = "Window"; //返回构造器名字
} else if (obj.nodeType === 9) {
result = "Document"; //返回构造器名字
} else if (obj.callee) {
result = "Arguments"; //返回构造器名字
} else if (isFinite(obj.length) && obj.item) {
result = "NodeList"; //处理节点集合
} else {
result = serialize.call(obj).slice(8, -1);
}
}
if (str) {
return str === result;
}
return result;
},
log: function(str, page, level) {
for (var i = 1, show = true; i < arguments.length; i++) {
level = arguments[i];
if (typeof level === "number") {
show = level <= $.config.level;
} else if (level === true) {
page = true;
}
}
if (show) {
if (page === true) {
$.require("ready", function() {
var div = DOC.createElement("pre");
div.className = "mass_sys_log";
div.innerHTML = str + ""; //确保为字符串
DOC.body.appendChild(div);
});
} else if (window.opera) {
opera.postError(str)
//http://www.cnblogs.com/zoho/archive/2013/01/31/2886651.html
//http://www.dotblogs.com.tw/littlebtc/archive/2009/04/06/ie8-ajax-2-debug.aspx
} else if (global.console && console.info && console.log) {
console.log(str);
}
}
return str;
},
oneObject: function(array, val) {
if (typeof array === "string") {
array = array.match($.rword) || [];
}
var result = {},
value = val !== void 0 ? val : 1;
for (var i = 0, n = array.length; i < n; i++) {
result[array[i]] = value;
}
return result;
},
config: function(settings) {
for (var p in settings) {
if (!hasOwn.call(settings, p))
continue;
var val = settings[p];
if (typeof kernel.plugin[p] === "function") {
kernel.plugin[p](val);
} else {
kernel[p] = val;
}
}
return this;
},
exports: function(name) {
global.$ = $$; //多库共存 2012.2.1之前为$$ &&(global.$ = $$)
name = name || $.config.nick; //取得当前简短的命名空间
$.config.nick = name;
global[NsKey] = NsVal;
return global[name] = this;
},
//一个空函数
noop: function() {
},
error: function(str, e) {
throw new (e || Error)(str);
}
});
(function() {
var cur = getCurrentScript(true);
if (!cur) {//处理window safari的Error没有stack的问题
cur = $.slice(document.scripts).pop().src;
}
var url = cur.replace(/[?#].*/, "");
kernel = $.config;
kernel.plugin = {};
kernel.alias = {};
basepath = kernel.base = url.slice(0, url.lastIndexOf("/") + 1);
var scripts = DOC.getElementsByTagName("script");
for (var i = 0, el; el = scripts[i++]; ) {
if (el.src === cur) {
kernel.nick = el.getAttribute("nick") || "$";
break;
}
}
kernel.level = 9;
})();
kernel.plugin["alias"] = function(val) {
var map = kernel.alias;
for (var c in val) {
if (hasOwn.call(val, c)) {
var prevValue = map[c];
var currValue = val[c];
if (prevValue) {
$.error("注意" + c + "出经重写过");
}
map[c] = currValue;
}
}
};
"Boolean,Number,String,Function,Array,Date,RegExp,Window,Document,Arguments,NodeList".replace($.rword, function(name) {
class2type["[object " + name + "]"] = name;
});
//============================加载系统===========================
var modules = $.modules = {
ready: {
exports: $
},
mass: {
state: 2,
exports: $
}
};
function getCurrentScript(base) {
// 参考 https://github.com/samyk/jiagra/blob/master/jiagra.js
var stack;
try {
a.b.c(); //强制报错,以便捕获e.stack
} catch (e) { //safari的错误对象只有line,sourceId,sourceURL
stack = e.stack;
if (!stack && window.opera) {
//opera 9没有e.stack,但有e.Backtrace,但不能直接取得,需要对e对象转字符串进行抽取
stack = (String(e).match(/of linked script \S+/g) || []).join(" ");
}
}
if (stack) {
stack = stack.split(/[@ ]/g).pop(); //取得最后一行,最后一个空格或@之后的部分
stack = stack[0] === "(" ? stack.slice(1, -1) : stack.replace(/\s/, ""); //去掉换行符
return stack.replace(/(:\d+)?:\d+$/i, ""); //去掉行号与或许存在的出错字符起始位置
}
var nodes = (base ? document : head).getElementsByTagName("script"); //只在head标签中寻找
for (var i = nodes.length, node; node = nodes[--i]; ) {
if ((base || node.className === moduleClass) && node.readyState === "interactive") {
return node.className = node.src;
}
}
}
function checkCycle(deps, nick) {
//检测是否存在循环依赖
for (var id in deps) {
if (deps[id] === "司徒正美" && modules[id].state !== 2 && (id === nick || checkCycle(modules[id].deps, nick))) {
return true;
}
}
}
function checkDeps() {
//检测此JS模块的依赖是否都已安装完毕,是则安装自身
loop: for (var i = loadings.length, id; id = loadings[--i]; ) {
var obj = modules[id],
deps = obj.deps;
for (var key in deps) {
if (hasOwn.call(deps, key) && modules[key].state !== 2) {
continue loop;
}
}
//如果deps是空对象或者其依赖的模块的状态都是2
if (obj.state !== 2) {
loadings.splice(i, 1); //必须先移除再安装,防止在IE下DOM树建完后手动刷新页面,会多次执行它
fireFactory(obj.id, obj.args, obj.factory);
checkDeps();//如果成功,则再执行一次,以防有些模块就差本模块没有安装好
}
}
}
function checkFail(node, onError, fuckIE) {
var id = node.src;//检测是否死链
node.onload = node.onreadystatechange = node.onerror = null;
if (onError || (fuckIE && !modules[id].state)) {
setTimeout(function() {
head.removeChild(node);
});
$.log("加载 " + id + " 失败" + onError + " " + (!modules[id].state), 7);
} else {
return true;
}
}
function loadJSCSS(url, parent, ret, shim) {
//1. 特别处理mass|ready标识符
if (/^(mass|ready)$/.test(url)) {
return url;
}
//2. 转化为完整路径
if ($.config.alias[url]) {//别名机制
ret = $.config.alias[url];
if (typeof ret === "object") {
shim = ret;
ret = ret.src;
}
} else {
if (/^(\w+)(\d)?:.*/.test(url)) { //如果本来就是完整路径
ret = url;
} else {
parent = parent.substr(0, parent.lastIndexOf('/'));
var tmp = url.charAt(0);
if (tmp !== "." && tmp !== "/") { //相对于根路径
ret = basepath + url;
} else if (url.slice(0, 2) === "./") { //相对于兄弟路径
ret = parent + url.slice(1);
} else if (url.slice(0, 2) === "..") { //相对于父路径
var arr = parent.replace(/\/$/, "").split("/");
tmp = url.replace(/\.\.\//g, function() {
arr.pop();
return "";
});
ret = arr.join("/") + "/" + tmp;
} else if (tmp === "/") {
ret = parent + url;//相对于兄弟路径
} else {
$.error("不符合模块标识规则: " + url);
}
}
}
var src = ret.replace(/[?#].*/, ""),
ext;
if (/\.(css|js)$/.test(src)) { // 处理"http://113.93.55.202/mass.draggable"的情况
ext = RegExp.$1;
}
if (!ext) { //如果没有后缀名,加上后缀名
src += ".js";
ext = "js";
}
//3. 开始加载JS或CSS
if (ext === "js") {
if (!modules[src]) { //如果之前没有加载过
modules[src] = {
id: src,
parent: parent,
exports: {}
};
if (shim) {//shim机制
require(shim.deps || "", function() {
loadJS(src, function() {
modules[src].state = 2;
modules[src].exports = typeof shim.exports === "function" ?
shim.exports() : window[shim.exports];
checkDeps();
});
});
} else {
loadJS(src);
}
}
return src;
} else {
loadCSS(src);
}
}
function loadJS(url, callback) {
//通过script节点加载目标模块
var node = DOC.createElement("script");
node.className = moduleClass; //让getCurrentScript只处理类名为moduleClass的script节点
node[W3C ? "onload" : "onreadystatechange"] = function() {
if (W3C || /loaded|complete/i.test(node.readyState)) {
//mass Framework会在_checkFail把它上面的回调清掉,尽可能释放回存,尽管DOM0事件写法在IE6下GC无望
var factory = factorys.pop();
factory && factory.delay(node.src);
if (callback) {
callback();
}
if (checkFail(node, false, !W3C)) {
$.log("已成功加载 " + node.src, 7);
}
}
};
node.onerror = function() {
checkFail(node, true);
};
node.src = url; //插入到head的第一个节点前,防止IE6下head标签没闭合前使用appendChild抛错
head.insertBefore(node, head.firstChild); //chrome下第二个参数不能为null
$.log("正准备加载 " + node.src, 7); //更重要的是IE6下可以收窄getCurrentScript的寻找范围
}
function loadCSS(url) {
//通过link节点加载模块需要的CSS文件
var id = url.replace(rmakeid, "");
if (!DOC.getElementById(id)) {
var node = DOC.createElement("link");
node.rel = "stylesheet";
node.href = url;
node.id = id;
head.insertBefore(node, head.firstChild);
}
}
window.require = $.require = function(list, factory, parent) {
// 用于检测它的依赖是否都为2
var deps = {},
// 用于保存依赖模块的返回值
args = [],
// 需要安装的模块数
dn = 0,
// 已安装完的模块数
cn = 0,
id = parent || "callback" + setTimeout("1");
parent = parent || basepath;
String(list).replace($.rword, function(el) {
var url = loadJSCSS(el, parent)
if (url) {
dn++;
if (modules[url] && modules[url].state === 2) {
cn++;
}
if (!deps[url]) {
args.push(url);
deps[url] = "司徒正美"; //去重
}
}
});
modules[id] = {//创建一个对象,记录模块的加载情况与其他信息
id: id,
factory: factory,
deps: deps,
args: args,
state: 1
};
if (dn === cn) { //如果需要安装的等于已安装好的
fireFactory(id, args, factory); //安装到框架中
} else {
//放到检测列队中,等待checkDeps处理
loadings.unshift(id);
}
checkDeps();
};
require.config = kernel;
window.define = $.define = function(id, deps, factory) { //模块名,依赖列表,模块本身
var args = $.slice(arguments);
if (typeof id === "string") {
var _id = args.shift();
}
if (typeof args[0] === "boolean") { //用于文件合并, 在标准浏览器中跳过补丁模块
if (args[0]) {
return;
}
args.shift();
}
if (typeof args[0] === "function") {
args.unshift([]);
} //上线合并后能直接得到模块ID,否则寻找当前正在解析中的script节点的src作为模块ID
//现在除了safari外,我们都能直接通过getCurrentScript一步到位得到当前执行的script节点,
//safari可通过onload+delay闭包组合解决
id = modules[id] && modules[id].state >= 1 ? _id : getCurrentScript();
factory = args[1];
factory.id = _id; //用于调试
factory.delay = function(id) {
args.push(id);
var isCycle = true;
try {
isCycle = checkCycle(modules[id].deps, id);
} catch (e) {
}
if (isCycle) {
$.error(id + "模块与之前的某些模块存在循环依赖");
}
delete factory.delay; //释放内存
require.apply(null, args); //0,1,2 --> 1,2,0
};
if (id) {
factory.delay(id, args);
} else { //先进先出
factorys.push(factory);
}
};
$.define.amd = modules;
function fireFactory(id, deps, factory) {
for (var i = 0, array = [], d; d = deps[i++]; ) {
array.push(modules[d].exports);
}
var module = Object(modules[id]),
ret = factory.apply(global, array);
module.state = 2;
if (ret !== void 0) {
modules[id].exports = ret;
}
return ret;
}
all.replace($.rword, function(a) {
$.config.alias["$" + a] = basepath + a + ".js";
});
//============================domReady机制===========================
var readyFn, ready = W3C ? "DOMContentLoaded" : "readystatechange";
function fireReady() {
modules.ready.state = 2;
checkDeps();
if (readyFn) {
$.unbind(DOC, ready, readyFn);
}
fireReady = $.noop; //隋性函数,防止IE9二次调用_checkDeps
}
function doScrollCheck() {
try { //IE下通过doScrollCheck检测DOM树是否建完
html.doScroll("left");
fireReady();
} catch (e) {
setTimeout(doScrollCheck);
}
}
;
//在firefox3.6之前,不存在readyState属性
//http://www.cnblogs.com/rubylouvre/archive/2012/12/18/2822912.html
if (!DOC.readyState) {
var readyState = DOC.readyState = "loading";
}
if (DOC.readyState === "complete") {
fireReady(); //如果在domReady之外加载
} else {
$.bind(DOC, ready, readyFn = function() {
if (W3C || DOC.readyState === "complete") {
fireReady();
if (readyState) { //IE下不能改写DOC.readyState
DOC.readyState = "complete";
}
}
});
if (html.doScroll) {
try { //如果跨域会报错,那时肯定证明是存在两个窗口
if (self.eval === parent.eval) {
doScrollCheck();
}
} catch (e) {
doScrollCheck();
}
}
}
//============================HTML5新标签支持===========================
//IE6789必须以硬编码形式把mass.js写在页面才生效
global.VBArray && ("abbr,article,aside,audio,base,bdi,canvas,data,datalist,details,figcaption,figure,footer," + "header,hgroup,m,mark,meter,nav,output,progress,section,summary,time,video").replace($.rword, function(tag) {
DOC.createElement(tag);
});
//============================HTML5无缝刷新页面支持======================
//https://developer.mozilla.org/en/DOM/window.onpopstate
$.bind(global, "popstate", function() {
NsKey = DOC.URL.replace(rmakeid, "");
$.exports();
});
$.exports($.config.nick + postfix); //防止不同版本的命名空间冲突
//============================合并核心模块支持===========================
var define = function(a) {
var array = [basepath + a + ".js"];//重写模块名;basepath变量为mass.js的一个变量
for (var i = 1; i < arguments.length; i++) {
var el = arguments[i];
if (typeof el !== "string") {//已经存在模块名了
array.push(el);
}
}
return $.define.apply($, array);
}
"lang,class,flow,data,query,support,css,attr,node,event,fx,ajax".replace($.rword, function(a) {
modules[basepath + a + ".js"] = {
state: 1
}
});
//=========================================
// 语言扩展模块v6 by 司徒正美
//=========================================
define("lang", /native code/.test(Array.isArray) ? ["mass"] : ["lang_fix"], function($) {
var global = this,
seval = global.execScript ? "execScript" : "eval",
rformat = /\\?\#{([^{}]+)\}/gm,
sopen = (global.open + '').replace(/open/g, ""),
defineProperty = Object.defineProperty;
function method(obj, name, val) {
if (!obj[name]) {
defineProperty(obj, name, {
configurable: true,
enumerable: false,
writable: true,
value: val
});
}
}
//IE8的Object.defineProperty只对DOM有效
try {
defineProperty({}, 'a', {
get: function() {
}
});
$.supportDefineProperty = true;
} catch (e) {
method = function(obj, name, method) {
if (!obj[name]) {
obj[name] = method;
}
};
}
function methods(obj, map) {
for (var name in map) {
method(obj, name, map[name]);
}
}
var tools = {
isPlainObject: function(obj) {
if (!$.type(obj, "Object") || $.isNative("reload", obj)) {
return false;
}
try { //不存在hasOwnProperty方法的对象肯定是IE的BOM对象或DOM对象
for (var key in obj) //只有一个方法是来自其原型立即返回flase
if (!Object.prototype.hasOwnProperty.call(obj, key)) { //不能用obj.hasOwnProperty自己查自己
return false;
}
} catch (e) {
return false;
}
return true;
},
isNative: function(method, obj) {
var m = obj ? obj[method] : false,
r = new RegExp(method, "g");
return !!(m && typeof m != "string" && sopen === (m + "").replace(r, ""));
},
isEmptyObject: function(obj) {
for (var i in obj) {
return false;
}
return true;
},
isArrayLike: function(obj, includeString) { //是否包含字符串
var type = $.type(obj);
if (type === "Array" || type === "Arguments" || type === "NodeList" || includeString && type === "String") {
return true;
}
if (type === "Object") {
var i = obj.length;
return (i >= 0) && (i % 1 === 0) && obj.hasOwnProperty("0"); //非负整数
}
return false;
},
isFunction: function(fn) {//为了性能起见,没有走$.type方法
return "[object Function]" === tools.toString.call(fn)
},
isArray: Array.isArray, //Array.isArray已在lang_fix中被修复
each: function(obj, fn, scope, map) {
var value, i = 0,
isArray = $.isArrayLike(obj),
ret = [];
if (isArray) {
for (var n = obj.length; i < n; i++) {
value = fn.call(scope || obj[i], i, obj[i]);
if (map) {
if (value != null) {
ret[ ret.length ] = value;
}
} else if (value === false) {
break;
}
}
} else {
for (i in obj) {
value = fn.call(scope || obj[i], i, obj[i]);
if (map) {
if (value != null) {
ret[ ret.length ] = value;
}
} else if (value === false) {
break;
}
}
}
return map ? ret : obj;
},
map: function(obj, fn, scope) {
return $.each(obj, fn, scope, true);
},
filter: function(obj, fn, scope) {
for (var i = 0, n = obj.length, ret = []; i < n; i++) {
var val = fn.call(scope || obj[i], obj[i], i);
if (!!val) {
ret[ret.length] = obj[i];
}
}
return ret;
},
format: function(str, object) {
var array = $.slice(arguments, 1);
return str.replace(rformat, function(match, name) {
if (match.charAt(0) === "\\")
return match.slice(1);
var index = Number(name);
if (index >= 0)
return array[index];
if (object && object[name] !== void 0)
return object[name];
return '';
});
},
range: function(start, end, step) {
step || (step = 1);
if (end == null) {
end = start || 0;
start = 0;
}
var index = -1,
length = Math.max(0, Math.ceil((end - start) / step)),
result = Array(length);
while (++index < length) {
result[index] = start;
start += step;
}
return result;
},
quote: String.quote || JSON.stringify,
dump: function(obj) {
var space = $.isNative("parse", window.JSON) ? 4 : "\r\t", cache = [],
text = JSON.stringify(obj, function(key, value) {
if (typeof value === 'object' && value !== null) {//防止环引用
if (cache.indexOf(value) !== -1) {
return;
}
cache.push(value);
}
return typeof value === "function" ? value + "" : value;
}, space);
cache = [];//GC回收
return text;
},
parseJS: function(code) {
//IE中,global.eval()和eval()一样只在当前作用域生效。
//Firefox,Safari,Opera中,直接调用eval()为当前作用域,global.eval()调用为全局作用域。
//window.execScript 在IE下一些限制条件
//http://www.ascadnetworks.com/Guides-and-Tips/IE-error-%2522Could-not-complete-the-operation-due-to-error-80020101%2522
if (code && /\S/.test(code)) {
try {
global[seval](code);
} catch (e) {
}
}
},
parseJSON: function(data) {
try {
return global.JSON.parse(data.trim());
} catch (e) {
$.error("Invalid JSON: " + data, TypeError);
}
},
parseXML: function(data, xml, tmp) {
try {
var mode = document.documentMode
if (global.DOMParser && (!mode || mode > 8)) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString(data, "text/xml");
} else { // IE
xml = new ActiveXObject("Microsoft.XMLDOM"); //"Microsoft.XMLDOM"
xml.async = "false";
xml.loadXML(data);
}
} catch (e) {
xml = undefined;
}
if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) {
$.error("Invalid XML: " + data, TypeError);
}
return xml;
}
}
$.mix(tools, false);
methods(String.prototype, {
repeat: function(n) {
//将字符串重复n遍
var result = "",
target = this;
while (n > 0) {
if (n & 1)
result += target;
target += target;
n >>= 1;
}
return result;
},
startsWith: function(str) {
//判定是否以给定字符串开头
return this.indexOf(str) === 0;
},
endsWith: function(str) {
//判定是否以给定字符串结尾
return this.lastIndexOf(str) === this.length - str.length;
},
contains: function(s, position) {
//判断一个字符串是否包含另一个字符
return ''.indexOf.call(this, s, position >> 0) !== -1;
}
});
//构建四个工具方法:$.String, $.Array, $.Number, $.Object
"String,Array,Number,Object".replace($.rword, function(Type) {
$[Type] = function(pack) {
var isNative = typeof pack == "string",
//取得方法名
methods = isNative ? pack.match($.rword) : Object.keys(pack);
methods.forEach(function(method) {
$[Type][method] = isNative ?
function(obj) {
return obj[method].apply(obj, $.slice(arguments, 1));
} : pack[method];
});
}
});
$.String({
byteLen: function(target) {
return target.replace(/[^\x00-\xff]/g, 'ci').length;
},
truncate: function(target, length, truncation) {
//length,新字符串长度,truncation,新字符串的结尾的字段,返回新字符串
length = length || 30;
truncation = truncation === void(0) ? "..." : truncation;
return target.length > length ? target.slice(0, length - truncation.length) + truncation : String(target);
},
camelize: function(target) {
//转换为驼峰风格
if (target.indexOf("-") < 0 && target.indexOf("_") < 0) {
return target; //提前判断,提高getStyle等的效率
}
return target.replace(/[-_][^-_]/g, function(match) {
return match.charAt(1).toUpperCase();
});
},
underscored: function(target) {
//转换为下划线风格
return target.replace(/([a-z\d])([A-Z]+)/g, "$1_$2").replace(/\-/g, "_").toLowerCase();
},
capitalize: function(target) {
//首字母大写
return target.charAt(0).toUpperCase() + target.substring(1).toLowerCase();
},
stripTags: function(target) {
//移除字符串中的html标签,但这方法有缺陷,如里面有script标签,会把这些不该显示出来的脚本也显示出来了
return target.replace(/<[^>]+>/g, "");
},
stripScripts: function(target) {
//移除字符串中所有的 script 标签。弥补stripTags方法的缺陷。此方法应在stripTags之前调用。
return target.replace(/<script[^>]*>([\S\s]*?)<\/script>/img, '');
},
escapeHTML: function(target) {
//将字符串经过 html 转义得到适合在页面中显示的内容, 例如替换 < 为 <
return target.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
},
unescapeHTML: function(target) {
//还原为可被文档解析的HTML标签
return target.replace(/"/g, '"').replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&") //处理转义的中文和实体字符
.replace(/&#([\d]+);/g, function($0, $1) {
return String.fromCharCode(parseInt($1, 10));
});
},
escapeRegExp: function(target) {
//http://stevenlevithan.com/regex/xregexp/
//将字符串安全格式化为正则表达式的源码
return(target + "").replace(/([-.*+?^${}()|[\]\/\\])/g, "\\$1");
},
pad: function(target, n, filling, right, radix) {
//http://www.cnblogs.com/rubylouvre/archive/2010/02/09/1666165.html
//在左边补上一些字符,默认为0
var num = target.toString(radix || 10);
filling = filling || "0";
while (num.length < n) {
if (!right) {
num = filling + num;
} else {
num += filling;
}
}
return num;
}
});
//字符串的原生原型方法
$.String("charAt,charCodeAt,concat,indexOf,lastIndexOf,localeCompare,match," + "contains,endsWith,startsWith,repeat," + //es6
"replace,search,slice,split,substring,toLowerCase,toLocaleLowerCase,toUpperCase,trim,toJSON")
$.Array({
contains: function(target, item) {
//判定数组是否包含指定目标。
return !!~target.indexOf(item);
},
removeAt: function(target, index) {
//移除数组中指定位置的元素,返回布尔表示成功与否。
return !!target.splice(index, 1).length
},
remove: function(target, item) {
//移除数组中第一个匹配传参的那个元素,返回布尔表示成功与否。
var index = target.indexOf(item);
if (~index)
return $.Array.removeAt(target, index);
return false;
},
shuffle: function(target) {
//对数组进行洗牌。若不想影响原数组,可以先拷贝一份出来操作。
var ret = [],
i = target.length,
n;
target = target.slice(0);
while (--i >= 0) {
n = Math.floor(Math.random() * i);
ret[ret.length] = target[n];
target[n] = target[i];
}
return ret;
},
random: function(target) {
//从数组中随机抽选一个元素出来。
return $.Array.shuffle(target.concat())[0];
},
flatten: function(target) {
//对数组进行平坦化处理,返回一个一维的新数组。
var result = [],
self = $.Array.flatten;
target.forEach(function(item) {
if (Array.isArray(item)) {
result = result.concat(self(item));