-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheventEmitter.js
43 lines (40 loc) · 1.01 KB
/
eventEmitter.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
/**
* Created by mengxt on 2015/3/14.
*/
//event代表事件名,listener 代表事件处理函数。方括号内的参数代表可选参数
function Event(){
}
Event.prototype.addListener = function(eventType,listener){
if(typeof listener !== 'function'){
throw TypeError('监听器必须是一个函数');
}
if(!this._events){
this._events = {};
}
if(this._events[type]){
this._events[type].push(listener);
}else{
this._events[type] = [listener];
}
};
Event.prototype.emit = function(type){
if(!this._events){
this._events = {};
}
var handler = this._events[type];
var arr = new Array(arguments.length-1);
for(var i = 0; i<arguments.length; i++){
arr[i-1] = arguments[i];
}
for(var j = 0; j<handler.length; j++){
handler[j].apply(this, arr);
}
}
function Boy(){
this.name = "mengxuetong";
}
Boy.prototype = new Event();
function Girl(){}
var meng = new Boy();
console.log(meng.name);
var zheng = new Girl();