xdyEvent.js
3.7 KB
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
(function () {
function processThis(fn, context) {
var outerArg = Array.prototype.slice.call(arguments, 2);
return function () {
var innerArg = Array.prototype.slice.call(arguments, 0);
fn.apply(context, outerArg.concat(innerArg));
}
}
function on(curEle, evenType, evenFn) {
if (/^xdy/.test(evenType)) {//->自定义的
if (!curEle["myBook" + evenType]) {
curEle["myBook" + evenType] = [];
}
var ary = curEle["myBook" + evenType];
for (var i = 0; i < ary.length; i++) {
if (ary[i] === evenFn) {
return;
}
}
ary.push(evenFn);
} else {//->内置的
if ("addEventListener" in window) {
curEle.addEventListener(evenType, evenFn, false);
return;
}
if (!curEle["myEvent" + evenType]) {
curEle["myEvent" + evenType] = [];
curEle.attachEvent("on" + evenType, processThis(run, curEle));
}
var ary = curEle["myEvent" + evenType];
for (var i = 0; i < ary.length; i++) {
if (ary[i] === evenFn) {
return;
}
}
ary.push(evenFn);
}
}
function run(e) {
e = e || window.event;
e.target = e.srcElement;
e.pageX = (document.documentElement.scrollLeft || document.body.scrollLeft) + e.clientX;
e.pageY = (document.documentElement.scrollTop || document.body.scrollTop) + e.clientY;
e.preventDefault = function () {
e.returnValue = false;
};
e.stopPropagation = function () {
e.cancelBubble = true;
};
var ary = this["myEvent" + e.type];
if (ary && ary instanceof Array) {
for (var i = 0; i < ary.length; i++) {
var tempFn = ary[i];
if (typeof tempFn === "function") {
tempFn.call(this, e);
} else {
ary.splice(i, 1);
i--;
}
}
}
}
function fire(evenType, e) {
var ary = this["myBook" + evenType];
if (ary && ary instanceof Array) {
for (var i = 0; i < ary.length; i++) {
var tempFn = ary[i];
if (typeof tempFn === "function") {
tempFn.call(this, e);
} else {
ary.splice(i, 1);
i--;
}
}
}
}
function off(curEle, evenType, evenFn) {
if (/^xdy/.test(evenType)) {
var ary = curEle["myBook" + evenType];
if (ary && ary instanceof Array) {
for (var i = 0; i < ary.length; i++) {
var tempFn = ary[i];
if (tempFn === evenFn) {
ary[i] = null;
return;
}
}
}
} else {
if ("removeEventListener" in window) {
curEle.removeEventListener(evenType, evenFn, false);
return;
}
var ary = curEle["myEvent" + evenType];
if (ary && ary instanceof Array) {
for (var i = 0; i < ary.length; i++) {
var tempFn = ary[i];
if (tempFn === evenFn) {
ary[i] = null;
return;
}
}
}
}
}
window.xdyEvent = window.$event = {
processThis: processThis,
on: on,
off: off,
fire: fire
};
})();