-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
115 lines (85 loc) · 2.6 KB
/
index.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// Emitter /////////////////////////////////////////////////////////////////////////////
function Emitter(obj) {
/* Emitter mixin */
if(obj) {
for(var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
obj._events = {};
return obj;
}
if(!(this instanceof Emitter)) {
return new Emitter();
}
this._events = {};
}
Emitter.prototype.listeners = function(event) {
var handlers = this._events[event];
if(!handlers) return [];
return handlers.filter(function(f){return f !==before && f !==after;});
};
Emitter.prototype.hasListeners = function(event) {
return this.listeners(event).length > 0;
};
Emitter.prototype.hasHandler = function(event,handler) {
return this.listeners(event).filter(function(f) {
return (f._of || f) !== handler;
}).length > 0;
};
function before(){}
function after(){}
Emitter.prototype.on = function(event,handler,first) {
var events = this._events[event];
if(!events) events = this._events[event] = [before,after];
if(first === true) events.splice(events.indexOf(before),0,handler);
else if(first === undefined) events.splice(events.indexOf(after),0,handler);
else events[events.length] = handler;
return this;
};
Emitter.prototype.before = function(event,handler) {
return this.on(event,handler,true);
};
Emitter.prototype.after = function(event,handler) {
return this.on(event,handler,false);
};
Emitter.prototype.off = function(event,handler) {
var listeners;
if(!arguments.length) {
this._events = {};
}
else {
if(!handler) {
this._events[event] = null;
} else if(this.hasListeners(event)){
this._events[event] = this._events[event].filter(function(f){
return (f._of ? f._of : f) !== handler;
});
}
}
return this;
};
Emitter.prototype.emit = function(event) {
var context, handler, args;
if(typeof event === 'object') {
context = event;
event = arguments[1];
}
args = Array.prototype.slice.call(arguments, (context ? 2 : 1));
handler = this.listeners(event);
context = context ? context : this;
for(var i = 0, l = handler.length; i < l; i++){
if(handler[i].apply(context,args) === false) break;
}
return this;
};
Emitter.prototype.once = function(event,handler) {
var self = this;
function once() {
self.off(event, handler);
handler.apply(this, arguments);
}
this.on(event, once);
once._of = handler;
return this;
};
module.exports = Emitter;