-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEventTarget.js
More file actions
46 lines (45 loc) · 1.14 KB
/
EventTarget.js
File metadata and controls
46 lines (45 loc) · 1.14 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
/*
*自定义事件
事件是JS与浏览器交互的重要途径。
事件的实质是观察者模式;对象可以发布事件用来表示在该对象的生命周期中的某个时刻
其他对象观察该对象,等待这个时刻到来并运行代码响应。
*/
//使用混合模式创建自定义类型对象
function EventTarget(){
//handler 用于储存事件处理程序
this.handle = {};
}
EventTarget.prototype = {
constructor:EventTarget,
//注册自定义事件
addHandler:function(type,handler){
if(typeof this.handle[type] == 'undefined'){
this.handle[type] = [];
}
this.handle[type].push(handler);
},
//触发自定义事件
trigger:function(event){
if(!event.target){
event.target = this;
}
if(this.handle[event.type] instanceof Array){
var handle = this.handle[event.type];
for(var i = 0;i<handle.length;i++){
handle[i](event);
}
}
},
//移除自定义事件
removeHandler:function(type,handler){
if(this.handle[type] instanceof Array){
var handle = this.handle[type];
for(var i = 0;i<handle.length;i++){
if(handle[i] === handler){
break;
}
}
handle.splice(i,1);
}
}
};