forked from RubyLouvre/avalon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
avalon.js
4695 lines (4541 loc) · 189 KB
/
avalon.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
/*==================================================
Copyright 2013-2014 司徒正美 and other contributors
http://www.cnblogs.com/rubylouvre/
https://github.com/RubyLouvre
http://weibo.com/jslouvre/
Released under the MIT license
avalon 1.3.4 2014.9.15
==================================================*/
(function(DOC) {
/*********************************************************************
* 全局变量及方法 *
**********************************************************************/
var prefix = "ms-"
var expose = new Date - 0
var subscribers = "$" + expose
//http://addyosmani.com/blog/understanding-mvvm-a-guide-for-javascript-developers/
var window = this || (0, eval)("this")
var otherRequire = window.require
var otherDefine = window.define
var stopRepeatAssign = false
var rword = /[^, ]+/g //切割字符串为一个个小块,以空格或豆号分开它们,结合replace实现字符串的forEach
var rnative = /\[native code\]/ //判定是否原生函数
var rcomplexType = /^(?:object|array)$/
var rwindow = /^\[object (?:Window|DOMWindow|global)\]$/
var oproto = Object.prototype
var ohasOwn = oproto.hasOwnProperty
var serialize = oproto.toString
var ap = Array.prototype
var aslice = ap.slice
var Registry = {} //将函数曝光到此对象上,方便访问器收集依赖
var W3C = window.dispatchEvent
var root = DOC.documentElement
var head = DOC.getElementsByTagName("head")[0] //HEAD元素
var hyperspace = DOC.createDocumentFragment()
var cinerator = DOC.createElement("div")
var class2type = {}
"Boolean Number String Function Array Date RegExp Object Error".replace(rword, function(name) {
class2type["[object " + name + "]"] = name.toLowerCase()
})
function noop() {
}
function log(a) {
if (window.console && avalon.config.debug) {
console.log(W3C ? a : a + "")
}
}
function oneObject(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
}
//生成UUID http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
function generateID() {
return "avalon" + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
}
/*********************************************************************
* avalon的静态方法定义区 *
**********************************************************************/
avalon = function(el) { //创建jQuery式的无new 实例化结构
return new avalon.init(el)
}
avalon.init = function(el) {
this[0] = this.element = el
}
avalon.fn = avalon.prototype = avalon.init.prototype
avalon.type = function(obj) {//取得目标的类型
if (obj == null) {
return String(obj)
}
// 早期的webkit内核浏览器实现了已废弃的ecma262v4标准,可以将正则字面量当作函数使用,因此typeof在判定正则时会返回function
return typeof obj === "object" || typeof obj === "function" ?
class2type[serialize.call(obj)] || "object" :
typeof obj
}
avalon.isWindow = function(obj) {
if (!obj)
return false
// 利用IE678 window == document为true,document == window竟然为false的神奇特性
// 标准浏览器及IE9,IE10等使用 正则检测
return obj == obj.document && obj.document != obj
}
function isWindow(obj) {
return rwindow.test(serialize.call(obj))
}
if (isWindow(window)) {
avalon.isWindow = isWindow
}
/*判定是否是一个朴素的javascript对象(Object),不是DOM对象,不是BOM对象,不是自定义类的实例*/
avalon.isPlainObject = function(obj, key) {
if (!obj || avalon.type(obj) !== "object" || obj.nodeType || avalon.isWindow(obj)) {
return false;
}
try {//IE内置对象没有constructor
if (obj.constructor &&
!ohasOwn.call(obj, "constructor") &&
!ohasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
return false;
}
} catch (e) {//IE8 9会在这里抛错
return false;
}
for (key in obj) {
}
return key === undefined || ohasOwn.call(obj, key);
}
if (rnative.test(Object.getPrototypeOf)) {
avalon.isPlainObject = function(obj) {
return !!obj && typeof obj === "object" && Object.getPrototypeOf(obj) === oproto
}
}
//与jQuery.extend方法,可用于浅拷贝,深拷贝
avalon.mix = avalon.fn.mix = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false
// 如果第一个参数为布尔,判定是否深拷贝
if (typeof target === "boolean") {
deep = target
target = arguments[1] || {}
i++
}
//确保接受方为一个复杂的数据类型
if (typeof target !== "object" && avalon.type(target) !== "function") {
target = {}
}
//如果只有一个参数,那么新成员添加于mix所在的对象上
if (i === length) {
target = this
i--
}
for (; i < length; i++) {
//只处理非空参数
if ((options = arguments[i]) != null) {
for (name in options) {
src = target[name]
copy = options[name]
// 防止环引用
if (target === copy) {
continue
}
if (deep && copy && (avalon.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false
clone = src && Array.isArray(src) ? src : []
} else {
clone = src && avalon.isPlainObject(src) ? src : {}
}
target[name] = avalon.mix(deep, clone, copy)
} else if (copy !== void 0) {
target[name] = copy
}
}
}
}
return target
}
function _number(a, len) { //用于模拟slice, splice的效果
a = Math.floor(a) || 0
return a < 0 ? Math.max(len + a, 0) : Math.min(a, len);
}
avalon.mix({
rword: rword,
subscribers: subscribers,
version: 1.35,
ui: {},
log: log,
slice: W3C ? function(nodes, start, end) {
return aslice.call(nodes, start, end)
} : function(nodes, start, end) {
var ret = []
var len = nodes.length
if (end === void 0)
end = len
if (typeof end === "number" && isFinite(end)) {
start = _number(start, len)
end = _number(end, len)
for (var i = start; i < end; ++i) {
ret[i - start] = nodes[i]
}
}
return ret
},
noop: noop,
/*如果不用Error对象封装一下,str在控制台下可能会乱码*/
error: function(str, e) {
throw new (e || Error)(str)
},
/*将一个以空格或逗号隔开的字符串或数组,转换成一个键值都为1的对象*/
oneObject: oneObject,
/* avalon.range(10)
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
avalon.range(1, 11)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
avalon.range(0, 30, 5)
=> [0, 5, 10, 15, 20, 25]
avalon.range(0, -10, -1)
=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
avalon.range(0)
=> []*/
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
},
eventHooks: {},
/*绑定事件*/
bind: function(el, type, fn, phase) {
var hooks = avalon.eventHooks
var hook = hooks[type]
if (typeof hook === "object") {
type = hook.type
if (hook.deel) {
fn = hook.deel(el, fn)
}
}
var callback = W3C ? fn : function(e) {
fn.call(el, fixEvent(e));
}
if (W3C) {
el.addEventListener(type, callback, !!phase)
} else {
el.attachEvent("on" + type, callback)
}
return callback
},
/*卸载事件*/
unbind: function(el, type, fn, phase) {
var hooks = avalon.eventHooks
var hook = hooks[type]
var callback = fn || noop
if (typeof hook === "object") {
type = hook.type
}
if (W3C) {
el.removeEventListener(type, callback, !!phase)
} else {
el.detachEvent("on" + type, callback)
}
},
/*读写删除元素节点的样式*/
css: function(node, name, value) {
if (node instanceof avalon) {
node = node[0]
}
var prop = /[_-]/.test(name) ? camelize(name) : name
name = avalon.cssName(prop) || prop
if (value === void 0 || typeof value === "boolean") { //获取样式
var fn = cssHooks[prop + ":get"] || cssHooks["@:get"]
var val = fn(node, name)
return value === true ? parseFloat(val) || 0 : val
} else if (value === "") { //请除样式
node.style[name] = ""
} else { //设置样式
if (value == null || value !== value) {
return
}
if (isFinite(value) && !avalon.cssNumber[prop]) {
value += "px"
}
fn = cssHooks[prop + ":set"] || cssHooks["@:set"]
fn(node, name, value)
}
},
/*遍历数组与对象,回调的第一个参数为索引或键名,第二个或元素或键值*/
each: function(obj, fn) {
if (obj) { //排除null, undefined
var i = 0
if (isArrayLike(obj)) {
for (var n = obj.length; i < n; i++) {
fn(i, obj[i])
}
} else {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
fn(i, obj[i])
}
}
}
}
},
//收集元素的data-{{prefix}}-*属性,并转换为对象
getWidgetData: function(elem, prefix) {
var raw = avalon(elem).data()
var result = {}
for (var i in raw) {
if (i.indexOf(prefix) === 0) {
result[i.replace(prefix, "").replace(/\w/, function(a) {
return a.toLowerCase()
})] = raw[i]
}
}
return result
},
Array: {
/*只有当前数组不存在此元素时只添加它*/
ensure: function(target, item) {
if (target.indexOf(item) === -1) {
target.push(item)
}
return target
},
/*移除数组中指定位置的元素,返回布尔表示成功与否*/
removeAt: function(target, index) {
return !!target.splice(index, 1).length
},
/*移除数组中第一个匹配传参的那个元素,返回布尔表示成功与否*/
remove: function(target, item) {
var index = target.indexOf(item)
if (~index)
return avalon.Array.removeAt(target, index)
return false
}
}
})
/*判定类数组,如节点集合,纯数组,arguments与拥有非负整数的length属性的纯JS对象*/
function isArrayLike(obj) {
if (obj && typeof obj === "object" && !avalon.isWindow(obj)) {
var n = obj.length
if (+n === n && !(n % 1) && n >= 0) { //检测length属性是否为非负整数
try {
if ({}.propertyIsEnumerable.call(obj, "length") === false) { //如果是原生对象
return Array.isArray(obj) || /^\s?function/.test(obj.item || obj.callee)
}
return true
} catch (e) { //IE的NodeList直接抛错
return true
}
}
}
return false
}
/*视浏览器情况采用最快的异步回调(在avalon.ready里,还有一个分支,用于处理IE6-9)*/
avalon.nextTick = window.setImmediate ? setImmediate.bind(window) : function(callback) {
setTimeout(callback, 0) //IE10-11 or W3C
}
/*********************************************************************
* modelFactory *
**********************************************************************/
//avalon最核心的方法的两个方法之一(另一个是avalon.scan),返回一个ViewModel(VM)
var VMODELS = avalon.vmodels = {}//所有vmodel都储存在这里
avalon.define = function(id, factory) {
var $id = id.$id || id
if (!$id) {
log("warning: vm必须指定$id")
}
if (VMODELS[id]) {
log("warning: " + $id + " 已经存在于avalon.vmodels中")
}
if (typeof id === "object") {
var model = modelFactory(id)
} else {
var scope = {
$watch: noop
}
factory(scope) //得到所有定义
model = modelFactory(scope) //偷天换日,将scope换为model
stopRepeatAssign = true
factory(model)
stopRepeatAssign = false
}
model.$id = $id
return VMODELS[$id] = model
}
function modelFactory(scope, model) {
if (Array.isArray(scope)) {
var arr = scope.concat()
scope.length = 0
var collection = Collection(scope)
collection.push.apply(collection, arr)
return collection
}
if (typeof scope.nodeType === "number") {
return scope
}
var vmodel = {} //要返回的对象
model = model || {} //放置$model上的属性
var accessingProperties = {} //监控属性
var normalProperties = {} //普通属性
var computedProperties = [] //计算属性
var watchProperties = arguments[2] || {} //强制要监听的属性
var skipArray = scope.$skipArray //要忽略监控的属性
for (var i = 0, name; name = skipProperties[i++]; ) {
delete scope[name]
normalProperties[name] = true
}
if (Array.isArray(skipArray)) {
for (var i = 0, name; name = skipArray[i++]; ) {
if (typeof name !== "string") {
log("warning:$skipArray[" + name + "] must be a string")
}
normalProperties[name] = true
}
}
for (var i in scope) {
accessorFactory(i, scope[i], model, normalProperties, accessingProperties, computedProperties, watchProperties)
}
vmodel = defineProperties(vmodel, descriptorFactory(accessingProperties), normalProperties) //生成一个空的ViewModel
for (var name in normalProperties) {
vmodel[name] = normalProperties[name]
}
watchProperties.vmodel = vmodel
vmodel.$model = model
vmodel.$events = {}
vmodel.$id = generateID()
vmodel.$accessors = accessingProperties
vmodel[subscribers] = []
for (var i in EventManager) {
var fn = EventManager [i]
if (!W3C) { //在IE6-8下,VB对象的方法里的this并不指向自身,需要用bind处理一下
fn = fn.bind(vmodel)
}
vmodel[i] = fn
}
vmodel.hasOwnProperty = function(name) {
return name in vmodel.$model
}
for (var i = 0, fn; fn = computedProperties[i++]; ) { //最后强逼计算属性 计算自己的值
Registry[expose] = fn
fn()
collectSubscribers(fn)
delete Registry[expose]
}
return vmodel
}
//一些不需要被监听的属性
var skipProperties = String("$id,$watch,$unwatch,$fire,$events,$model,$skipArray,$accessors," + subscribers).match(rword)
//比较两个值是否相等
var isEqual = Object.is || function(v1, v2) {
if (v1 === 0 && v2 === 0) {
return 1 / v1 === 1 / v2
} else if (v1 !== v1) {
return v2 !== v2
} else {
return v1 === v2
}
}
function safeFire(a, b, c, d) {
if (a.$events) {
EventManager.$fire.call(a, b, c, d)
}
}
var descriptorFactory = W3C ? function(obj) {
var descriptors = {}
for (var i in obj) {
descriptors[i] = {
get: obj[i],
set: obj[i],
enumerable: true,
configurable: true
}
}
return descriptors
} : function(a) {
return a
}
//循环生成访问器属性需要的setter, getter函数(这里统称为accessor)
function accessorFactory(name, val, model, normalProperties, accessingProperties, computedProperties, watchProperties) {
model[name] = val
// 如果是元素节点 或者 在全局的skipProperties里 或者在当前的$skipArray里
// 或者是以$开头并又不在watchPropertie里,这些属性是不会产生accessor
if (normalProperties[name] || (val && val.nodeType) || (name.charAt(0) === "$" && !watchProperties[name])) {
return normalProperties[name] = val
}
// 此外, 函数也不会产生accessor
var valueType = avalon.type(val)
if (valueType === "function") {
return normalProperties[name] = val
}
//总共产生三种accessor
var accessor, oldArgs
if (valueType === "object" && typeof val.get === "function" && Object.keys(val).length <= 2) {
var setter = val.set,
getter = val.get
//第1种对应计算属性, 因变量,通过其他监控属性触发其改变
accessor = function(newValue) {
var vmodel = watchProperties.vmodel
var value = model[name],
preValue = value
if (arguments.length) {
if (stopRepeatAssign) {
return
}
if (typeof setter === "function") {
var backup = vmodel.$events[name]
vmodel.$events[name] = [] //清空回调,防止内部冒泡而触发多次$fire
setter.call(vmodel, newValue)
vmodel.$events[name] = backup
}
if (!isEqual(oldArgs, newValue)) {
oldArgs = newValue
newValue = model[name] = getter.call(vmodel) //同步$model
withProxyCount && updateWithProxy(vmodel.$id, name, newValue) //同步循环绑定中的代理VM
notifySubscribers(accessor) //通知顶层改变
safeFire(vmodel, name, newValue, preValue) //触发$watch回调
}
} else {
if (avalon.openComputedCollect) { // 收集视图刷新函数
collectSubscribers(accessor)
}
newValue = model[name] = getter.call(vmodel)
if (!isEqual(value, newValue)) {
oldArgs = void 0
safeFire(vmodel, name, newValue, preValue)
}
return newValue
}
}
computedProperties.push(accessor)
} else if (rcomplexType.test(valueType)) {
//第2种对应子ViewModel或监控数组
accessor = function(newValue) {
var realAccessor = accessor.$vmodel,
preValue = realAccessor.$model
if (arguments.length) {
if (stopRepeatAssign) {
return
}
if (!isEqual(preValue, newValue)) {
newValue = accessor.$vmodel = updateVModel(realAccessor, newValue, valueType)
var fn = rebindings[newValue.$id]
fn && fn() //更新视图
var parent = watchProperties.vmodel
model[name] = newValue.$model //同步$model
notifySubscribers(realAccessor) //通知顶层改变
safeFire(parent, name, model[name], preValue) //触发$watch回调
}
} else {
collectSubscribers(realAccessor) //收集视图函数
return realAccessor
}
}
accessor.$vmodel = val.$model ? val : modelFactory(val, val)
model[name] = accessor.$vmodel.$model
} else {
//第3种对应简单的数据类型,自变量,监控属性
accessor = function(newValue) {
var preValue = model[name]
if (arguments.length) {
if (!isEqual(preValue, newValue)) {
model[name] = newValue //同步$model
var vmodel = watchProperties.vmodel
withProxyCount && updateWithProxy(vmodel.$id, name, newValue) //同步循环绑定中的代理VM
notifySubscribers(accessor) //通知顶层改变
safeFire(vmodel, name, newValue, preValue) //触发$watch回调
}
} else {
collectSubscribers(accessor) //收集视图函数
return preValue
}
}
model[name] = val
}
accessor[subscribers] = [] //订阅者数组
accessingProperties[name] = accessor
}
//ms-with, ms-repeat绑定生成的代理对象储存池
var withProxyPool = {}
var withProxyCount = 0
var rebindings = {}
function updateWithProxy($id, name, val) {
var pool = withProxyPool[$id]
if (pool && pool[name]) {
pool[name].$val = val
}
}
//应用于第2种accessor
function updateVModel(a, b, valueType) {
//a为原来的VM, b为新数组或新对象
if (valueType === "array") {
if (!Array.isArray(b)) {
return a //fix https://github.com/RubyLouvre/avalon/issues/261
}
var bb = b.concat()
a.clear()
a.push.apply(a, bb)
return a
} else {
var iterators = a[subscribers] || []
if (withProxyPool[a.$id]) {
withProxyCount--
delete withProxyPool[a.$id]
}
var ret = modelFactory(b)
rebindings[ret.$id] = function(data) {
while (data = iterators.shift()) {
(function(el) {
if (el.type) { //重新绑定
avalon.nextTick(function() {
el.rollback && el.rollback() //还原 ms-with ms-on
bindingHandlers[el.type](el, el.vmodels)
})
}
})(data)
}
delete rebindings[ret.$id]
}
return ret
}
}
//===================修复浏览器对Object.defineProperties的支持=================
var defineProperty = Object.defineProperty
//如果浏览器不支持ecma262v5的Object.defineProperties或者存在BUG,比如IE8
//标准浏览器使用__defineGetter__, __defineSetter__实现
try {
defineProperty({}, "_", {
value: "x"
})
var defineProperties = Object.defineProperties
} catch (e) {
if ("__defineGetter__" in avalon) {
defineProperty = function(obj, prop, desc) {
if ('value' in desc) {
obj[prop] = desc.value
}
if ("get" in desc) {
obj.__defineGetter__(prop, desc.get)
}
if ('set' in desc) {
obj.__defineSetter__(prop, desc.set)
}
return obj
}
defineProperties = function(obj, descs) {
for (var prop in descs) {
if (descs.hasOwnProperty(prop)) {
defineProperty(obj, prop, descs[prop])
}
}
return obj
}
}
}
//IE6-8使用VBScript类的set get语句实现
if (!defineProperties && window.VBArray) {
window.execScript([
"Function parseVB(code)",
"\tExecuteGlobal(code)",
"End Function",
"Dim VBClassBodies",
"Set VBClassBodies=CreateObject(\"Scripting.Dictionary\")",
"Function findOrDefineVBClass(name,body)",
"\tDim found",
"\tfound=\"\"",
"\tFor Each key in VBClassBodies",
"\t\tIf body=VBClassBodies.Item(key) Then",
"\t\t\tfound=key",
"\t\t\tExit For",
"\t\tEnd If",
"\tnext",
"\tIf found=\"\" Then",
"\t\tparseVB(\"Class \" + name + body)",
"\t\tVBClassBodies.Add name, body",
"\t\tfound=name",
"\tEnd If",
"\tfindOrDefineVBClass=found",
"End Function"
].join("\n"), "VBScript")
function VBMediator(accessingProperties, name, value) {
var accessor = accessingProperties[name]
if (typeof accessor === "function") {
if (arguments.length === 3) {
accessor(value)
} else {
return accessor()
}
}
}
defineProperties = function(name, accessingProperties, normalProperties) {
var className = "VBClass" + setTimeout("1"),
buffer = []
buffer.push(
"\r\n\tPrivate [__data__], [__proxy__]",
"\tPublic Default Function [__const__](d, p)",
"\t\tSet [__data__] = d: set [__proxy__] = p",
"\t\tSet [__const__] = Me", //链式调用
"\tEnd Function")
//添加普通属性,因为VBScript对象不能像JS那样随意增删属性,必须在这里预先定义好
for (name in normalProperties) {
buffer.push("\tPublic [" + name + "]")
}
buffer.push("\tPublic [" + 'hasOwnProperty' + "]")
//添加访问器属性
for (name in accessingProperties) {
if (!(name in normalProperties)) { //防止重复定义
buffer.push(
//由于不知对方会传入什么,因此set, let都用上
"\tPublic Property Let [" + name + "](val" + expose + ")", //setter
"\t\tCall [__proxy__]([__data__], \"" + name + "\", val" + expose + ")",
"\tEnd Property",
"\tPublic Property Set [" + name + "](val" + expose + ")", //setter
"\t\tCall [__proxy__]([__data__], \"" + name + "\", val" + expose + ")",
"\tEnd Property",
"\tPublic Property Get [" + name + "]", //getter
"\tOn Error Resume Next", //必须优先使用set语句,否则它会误将数组当字符串返回
"\t\tSet[" + name + "] = [__proxy__]([__data__],\"" + name + "\")",
"\tIf Err.Number <> 0 Then",
"\t\t[" + name + "] = [__proxy__]([__data__],\"" + name + "\")",
"\tEnd If",
"\tOn Error Goto 0",
"\tEnd Property")
}
}
buffer.push("End Class")
var code = buffer.join("\r\n"),
realClassName = window['findOrDefineVBClass'](className, code) //如果该VB类已定义,返回类名。否则用className创建一个新类。
if (realClassName === className) {
window.parseVB([
"Function " + className + "Factory(a, b)", //创建实例并传入两个关键的参数
"\tDim o",
"\tSet o = (New " + className + ")(a, b)",
"\tSet " + className + "Factory = o",
"End Function"
].join("\r\n"))
}
var ret = window[realClassName + "Factory"](accessingProperties, VBMediator) //得到其产品
return ret //得到其产品
}
}
/*********************************************************************
* javascript 底层补丁 *
**********************************************************************/
if (!"司徒正美".trim) {
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g
String.prototype.trim = function() {
return this.replace(rtrim, "")
}
}
var hasDontEnumBug = !({'toString': null}).propertyIsEnumerable('toString'),
hasProtoEnumBug = (function() {
}).propertyIsEnumerable('prototype'),
dontEnums = [
"toString",
"toLocaleString",
"valueOf",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"constructor"
],
dontEnumsLength = dontEnums.length;
if (!Object.keys) {
Object.keys = function(object) { //ecma262v5 15.2.3.14
var theKeys = [];
var skipProto = hasProtoEnumBug && typeof object === "function"
if (typeof object === "string" || (object && object.callee)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i))
}
} else {
for (var name in object) {
if (!(skipProto && name === "prototype") && ohasOwn.call(object, name)) {
theKeys.push(String(name))
}
}
}
if (hasDontEnumBug) {
var ctor = object.constructor,
skipConstructor = ctor && ctor.prototype === object;
for (var j = 0; j < dontEnumsLength; j++) {
var dontEnum = dontEnums[j]
if (!(skipConstructor && dontEnum === "constructor") && ohasOwn.call(object, dontEnum)) {
theKeys.push(dontEnum)
}
}
}
return theKeys
}
}
if (!Array.isArray) {
Array.isArray = function(a) {
return a && avalon.type(a) === "array"
}
}
if (!noop.bind) {
Function.prototype.bind = function(scope) {
if (arguments.length < 2 && scope === void 0)
return this
var fn = this,
argv = arguments
return function() {
var args = [],
i
for (i = 1; i < argv.length; i++)
args.push(argv[i])
for (i = 0; i < arguments.length; i++)
args.push(arguments[i])
return fn.apply(scope, args)
}
}
}
function iterator(vars, body, ret) {
var fun = 'for(var ' + vars + 'i=0,n = this.length; i < n; i++){' + body.replace('_', '((i in this) && fn.call(scope,this[i],i,this))') + '}' + ret
return Function("fn,scope", fun)
}
if (!rnative.test([].map)) {
avalon.mix(ap, {
//定位操作,返回数组中第一个等于给定参数的元素的索引值。
indexOf: function(item, index) {
var n = this.length,
i = ~~index
if (i < 0)
i += n
for (; i < n; i++)
if (this[i] === item)
return i
return -1
},
//定位操作,同上,不过是从后遍历。
lastIndexOf: function(item, index) {
var n = this.length,
i = index == null ? n - 1 : index
if (i < 0)
i = Math.max(0, n + i)
for (; i >= 0; i--)
if (this[i] === item)
return i
return -1
},
//迭代操作,将数组的元素挨个儿传入一个函数中执行。Prototype.js的对应名字为each。
forEach: iterator("", '_', ""),
//迭代类 在数组中的每个项上运行一个函数,如果此函数的值为真,则此元素作为新数组的元素收集起来,并返回新数组
filter: iterator('r=[],j=0,', 'if(_)r[j++]=this[i]', 'return r'),
//收集操作,将数组的元素挨个儿传入一个函数中执行,然后把它们的返回值组成一个新数组返回。Prototype.js的对应名字为collect。
map: iterator('r=[],', 'r[i]=_', 'return r'),
//只要数组中有一个元素满足条件(放进给定函数返回true),那么它就返回true。Prototype.js的对应名字为any。
some: iterator("", 'if(_)return true', 'return false'),
//只有数组中的元素都满足条件(放进给定函数返回true),它才返回true。Prototype.js的对应名字为all。
every: iterator("", 'if(!_)return false', 'return true')
})
}
/*********************************************************************
* DOM 底层补丁 *
**********************************************************************/
function fixContains(a, b) {
if (b) {
while ((b = b.parentNode)) {
if (b === a) {
return true;
}
}
}
return false;
}
//safari5+是把contains方法放在Element.prototype上而不是Node.prototype
if (!root.contains) {
Node.prototype.contains = function(arg) {
return !!(this.compareDocumentPosition(arg) & 16)
}
}
//IE6-11的文档对象没有contains
if (!DOC.contains) {
DOC.contains = function(b) {
return fixContains(this, b)
}
}
function outerHTML() {
return new XMLSerializer().serializeToString(this)
}
if (window.SVGElement) {
var svgns = "http://www.w3.org/2000/svg"
var svg = document.createElementNS(svgns, "svg")
svg.innerHTML = '<circle cx="50" cy="50" r="40" fill="yellow" />'
if (svg.firstChild !== "[object SVGCircleElement]") {// #409
function enumerateNode(node, targetNode) {
if (node && node.childNodes) {
var nodes = node.childNodes
for (var i = 0, el; el = nodes[i++]; ) {
if (el.tagName) {
var svg = document.createElementNS(svgns,
el.tagName.toLowerCase())
ap.forEach.call(el.attributes, function(attr) {
svg.setAttribute(attr.name, attr.value)//复制属性
})
// 递归处理子节点
enumerateNode(el, svg)
targetNode.appendChild(svg)
}
}
}
}
Object.defineProperties(SVGElement.prototype, {
"outerHTML": {//IE9-11,firefox不支持SVG元素的innerHTML,outerHTML属性
enumerable: true,
configurable: true,
get: outerHTML,
set: function(html) {
var tagName = this.tagName.toLowerCase(),
par = this.parentNode,
frag = avalon.parseHTML(html)
// 操作的svg,直接插入
if (tagName === "svg") {
par.insertBefore(frag, this)
// svg节点的子节点类似
} else {
var newFrag = document.createDocumentFragment()
enumerateNode(frag, newFrag)
par.insertBefore(newFrag, this)
}
par.removeChild(this)
}
},
"innerHTML": {
enumerable: true,
configurable: true,
get: function() {
var s = this.outerHTML
var ropen = new RegExp("<" + this.nodeName + '\\b(?:(["\'])[^"]*?(\\1)|[^>])*>', "i")
var rclose = new RegExp("<\/" + this.nodeName + ">$", "i")
return s.replace(ropen, "").replace(rclose, "")
},
set: function(html) {
if (avalon.clearHTM) {
avalon.clearHTML(this)
var frag = avalon.parseHTML(html)
enumerateNode(frag, this)
}
}
}
})
}
}
if (!root.outerHTML && window.HTMLElement) { //firefox 到11时才有outerHTML
HTMLElement.prototype.__defineGetter__("outerHTML", outerHTML);
}
/*********************************************************************
* 配置系统 *
**********************************************************************/
function kernel(settings) {
for (var p in settings) {
if (!ohasOwn.call(settings, p))
continue
var val = settings[p]
if (typeof kernel.plugins[p] === "function") {
kernel.plugins[p](val)
} else if (typeof kernel[p] === "object") {
avalon.mix(kernel[p], val)
} else {
kernel[p] = val
}
}
return this
}
var openTag, closeTag, rexpr, rexprg, rbind, rregexp = /[-.*+?^${}()|[\]\/\\]/g
function escapeRegExp(target) {
//http://stevenlevithan.com/regex/xregexp/
//将字符串安全格式化为正则表达式的源码
return (target + "").replace(rregexp, "\\$&")
}
var plugins = {
loader: function(builtin) {