-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.class.js
70 lines (58 loc) · 2.49 KB
/
index.class.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
class EventsClassMixin {
_subscriptions = {}
on () {
return this.subscribe.apply(this, arguments)
}
subscribe (eventName, subscriptionCallback, ...subscriptionParams) {
// check
if (arguments.length < 2)
throw new Error(`.subscribe() expects at least two arguments, the event name and the subscription callback.`)
if (typeof arguments[0] !== 'string')
throw new TypeError('.subscribe() expects a string for the event name.')
if (typeof arguments[1] !== 'function')
throw new TypeError('.subscribe() expects a function for the subscription callback.')
// register event
if (eventName in this._subscriptions === false)
this._subscriptions[eventName] = []
// add subscription
let subscriptionId = Symbol(`Subscription for the event '${eventName}'`)
this._subscriptions[eventName].push({
id: subscriptionId,
fn: subscriptionCallback,
pr: subscriptionParams
})
return subscriptionId
}
off () {
this.unsubscribe.apply(this, arguments)
}
unsubscribe (subscriptionId, eventName) {
// check
if (arguments.length !== 2)
throw new Error('.unsubscribe() expects exactly two arguments, the subscription id and the event name.')
if (typeof arguments[0] !== 'symbol')
throw new TypeError('.unsubscribe() expects a Symbol for the subscription id.')
if (typeof arguments[1] !== 'string')
throw new TypeError('.unsubscribe() expects a string for the event name.')
// remove subscription
if (eventName in this._subscriptions)
this._subscriptions[eventName] = this._subscriptions[eventName].filter(subscription => subscription.id !== subscriptionId)
}
emit () {
this.publish.apply(this, arguments)
}
publish (eventName, ...eventParams) {
// check
if (arguments.length < 1)
throw new Error('.publish() expects at least one argument, the event name.')
if (typeof arguments[0] !== 'string')
throw new TypeError('.publish() expects a string for the event name.')
// pick up latches
if (eventName in this._subscriptions) {
this._subscriptions[eventName].forEach(subscription => {
subscription.fn.apply(this, [].concat(eventParams, subscription.pr))
})
}
}
}
module.exports = EventsClassMixin