-
Notifications
You must be signed in to change notification settings - Fork 0
/
EventEmitter.js
91 lines (80 loc) · 2.02 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
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
(function () {
function isValidListener (listener) {
if (typeof listener === 'function') {
return true;
} else if (listener && typeof listener === 'object') {
return isValidListener(listener.listener);
} else {
return false;
}
}
function indexOf (events, listener) {
if (typeof listener === 'object') {
listener = listener.listener;
}
var index = -1;
for (var i = 0; i < events.length; i ++) {
if (events[i].listener === listener) {
index = i;
break;
}
}
return index;
}
function EventEmitter () {
this._events = {}
}
var proto = EventEmitter.prototype
proto.on = function (event, listener) {
if (!event || !listener) return;
if (!isValidListener(listener)) return;
var events = this._events[event] = this._events[event] || [];
if (indexOf(events, listener) != -1) return;
if (typeof listener === 'function') {
events.push({
listener: listener,
once: false
});
} else {
events.push(listener);
}
return this
}
proto.once = function (event, listener) {
this.on(event, {
listener: listener,
once: true
})
return this
}
proto.off = function (event, listener) {
if(!event || !listener) return;
if (!this._events[event]) return;
var events = this._events[event]
var index = indexOf(events, listener);
if (index === -1) return;
events.splice(index, 1);
return this;
}
proto.emit = function (event, args) {
if (!event) return;
if (!this._events[event]) return;
var listents = this._events[event];
for (var i = 0; i < listents.length; i ++) {
listents[i].listener.apply(this, args || []);
if (listents[i].once) {
listents.splice(i, 1);
}
}
return this;
}
proto.allOff = function (event) {
if (event && this._events[event]) {
this._events[event] = [];
} else {
this._events = {}
}
return this;
}
window.EventEmitter = EventEmitter;
})()