forked from StephanHoyer/smoke-signal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (53 loc) · 1.17 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
'use strict'
function signal (options) {
var listeners = []
var api = {
push: function (listener) {
if (listeners.indexOf(listener) < 0) {
listeners.push(listener)
}
return {
pause: function () {
api.pull(listener)
},
resume: function () {
api.push(listener)
}
}
},
pull: function (listener) {
var index = listeners.indexOf(listener)
if (index > -1) {
listeners.splice(index, 1)
}
return api
},
once: function (listener) {
var handler = api.push(function () {
listener.apply(null, arguments)
handler.pause()
})
return handler
},
trigger: function () {
var args = arguments;
[].concat(listeners).map(function (listener) {
try {
listener.apply(null, args)
} catch (e) {
if (options && options.onError) {
options.onError(e)
} else if (options && options.logExceptions) {
console.error(e)
}
}
})
return api
},
clear: function () {
listeners = []
}
}
return api
}
module.exports = signal