-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEventTarget.js
46 lines (43 loc) · 1.16 KB
/
EventTarget.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
/**
* @desc 定义自定义的事件
* @param {String} type 事件类型
* @param {function} handler 事件回调函数
* @return {Object} 事件与事件回调函数的对象
*/
function EventTarget() {
this.handlers = {};
}
EventTarget.prototype = {
constructor : EventTarget,
//添加自定义事件
addHandler : function (type, handler) {
if (typeof this.handlers[type] == "undefined") {
this.handlers[type] = [];
}
this.handlers[type].push(handler);
},
//触发事件
fire : function (event) {
if (!event.target) {
event.target = this;
}
if (this.handlers[event.type] instanceof Array) {
var handlers = this.handlers[event.type];
for (var i = 0, len = handlers.length; i < len; i++) {
handlers[i](event);
}
}
},
//移除已添加的事件回调函数,即移除对应的事件
removeHandler : function (type, handler) {
if (this.handlers[type] instanceof Array) {
var handlers = this.handlers[type];
for (var i = 0, len = handlers.length; i < len; i++) {
if (handlers[i] === handler) {
break;
}
}
handlers.splice(i, 1);
}
}
};