-
Notifications
You must be signed in to change notification settings - Fork 2
/
Event.js
105 lines (81 loc) · 2.46 KB
/
Event.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
/**
* Class Event
* https://github.com/huya-fed/Event
*/
var arr = []
var slice = arr.slice
var isFunction = function (f) {
return typeof f === 'function'
}
var isString = function (s) {
return typeof s === 'string'
}
function E () {
return {
fired: false,
data: [],
callbacks: new $.Callbacks()
}
}
function Event () {
var events = {}
function on (name, callback, useCache) {
if ( !isString(name) || !isFunction(callback) ) return this;
var e = events[name] || ( events[name] = new E() )
e.callbacks.add(callback)
if (useCache && e.fired) {
callback.apply(this, e.data)
}
return this
}
function emit (name) {
if ( !isString(name) ) return this;
var e = events[name] || ( events[name] = new E() )
e.fired = true
e.data = slice.call(arguments, 1)
e.callbacks.fireWith(this, e.data)
if (name !== 'ALL') {
emit.apply( this, ['ALL'].concat( slice.call(arguments) ) )
}
return this
}
function off (name, callback) {
var l = arguments.length
if (l === 0) {
for (var p in events) {
if ( events.hasOwnProperty(p) ) {
events[p].callbacks.empty()
}
}
} else {
if ( isString(name) ) {
var e = events[name]
if (e) {
if (l === 1) {
e.callbacks.empty()
} else {
if ( isFunction(callback) ) {
e.callbacks.remove(callback)
}
}
}
}
}
return this
}
function one (name, callback, useCache) {
if ( !isString(name) || !isFunction(callback) ) return this;
var proxy = function () {
callback.apply(this, arguments)
off(name, proxy)
}
on(name, proxy, useCache)
}
return {
on: on,
one: one,
off: off,
emit: emit
}
}
return Event