-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path发布订阅.js
53 lines (47 loc) · 921 Bytes
/
发布订阅.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
var Event = (function () {
var clientList = {},
listen,
trigger,
remove
listen = function (key, fn) {
if (!clientList[key]) {
clientList[key] = []
}
clientList[key].push(fn)
}
trigger = function () {
var key = [].shift.call(arguments),
fns = clientList[key]
if (!fns || fns.length === 0) {
return false
}
for (var i = 0, fn; fn = fns[i++];) {
fn.apply(this, arguments)
}
}
remove = function (key, fn) {
var fns = clientList[key]
if (!fns) {
return false
}
if (!fn) {
fns.length = 0
} else {
for (var l = fns.length - 1; l >= 0; l--) {
var _fn = fns[l]
if (_fn === fn) {
fns.splice(l, 1)
}
}
}
}
return {
listen,
trigger,
remove
}
})()
Event.listen('event1', function (a) {
console.log('event1: ' + a)
})
Event.trigger('event1', 123)