-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
91 lines (72 loc) · 1.68 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
import { LOG_LEVEL } from 'uc-log'
function indexOfHandler(handlers, h) {
let i = handlers.length;
while (i--) {
const hh = handlers[i];
if (hh.h === h.h) {
if ((hh.c && hh.c === h.c) || (h.c && h.c === hh.c) || (!hh.c && !h.c)) {
return i;
}
}
}
return -1;
}
export default {
on: function(event, handler, context) {
const h = {
h: handler
}
if (context) {
h.c = context;
}
let handlers = this.events[event];
if (!handlers) {
handlers = this.events[event] = [];
}
if (indexOfHandler(handlers, h) === -1) {
handlers.push(h);
}
this.log && this.log(LOG_LEVEL.INFO, h.once ? 'once' : 'on', event);
return this;
},
off: function(event, handler, context) {
this.log && this.log(LOG_LEVEL.INFO, 'off', event);
const handlers = this.events[event];
if (!handlers) {
return this;
}
const h = {
h: handler
}
if (context) {
h.c = context;
}
const index = indexOfHandler(handlers, h);
if (index !== -1) {
handlers.splice(index, 1);
}
if (handlers.length === 0) {
delete this.events[event];
}
return this;
},
once: function(event, handler, context) {
const once = (...args) => {
this.off(event, once);
handler.apply(context, args);
}
this.on(event, once);
return this;
},
emit: function(event, ...args) {
this.log && this.log(LOG_LEVEL.INFO, 'emit', event, ...args);
const handlers = this.events[event];
if (!handlers || !handlers.length) {
return this;
}
handlers.slice().forEach(ctx => {
ctx.h.apply(ctx.c, args);
});
return this;
}
};