-
Notifications
You must be signed in to change notification settings - Fork 25
/
ActionListeners.js
65 lines (58 loc) · 1.63 KB
/
ActionListeners.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
/**
* ActionListeners(alt: AltInstance): ActionListenersInstance
*
* > Globally listen to individual actions
*
* If you need to listen to an action but don't want the weight of a store
* then this util is what you can use.
*
* Usage:
*
* ```js
* var actionListener = new ActionListeners(alt);
*
* actionListener.addActionListener(Action.ACTION_NAME, function (data) {
* // do something with data
* })
* ```
*/
import { isFunction } from './functions';
function ActionListeners(alt) {
this.dispatcher = alt.dispatcher
this.listeners = {}
}
/*
* addActionListener(symAction: symbol, handler: function): number
* Adds a listener to a specified action and returns the dispatch token.
*/
ActionListeners.prototype.addActionListener = function addActionListener(symAction, handler) {
if (!isFunction(handler)) {
throw new Error('addActionListener() expects a function as the second argument')
}
const id = this.dispatcher.register((payload) => {
/* istanbul ignore else */
if (symAction === payload.action) {
handler(payload.data, payload.details)
}
})
this.listeners[id] = true
return id
}
/*
* removeActionListener(id: number): undefined
* Removes the specified dispatch registration.
*/
ActionListeners.prototype.removeActionListener = function removeActionListener(id) {
delete this.listeners[id]
this.dispatcher.unregister(id)
}
/**
* Remove all listeners.
*/
ActionListeners.prototype.removeAllActionListeners = function removeAllActionListeners() {
Object.keys(this.listeners).forEach(
this.removeActionListener.bind(this)
)
this.listeners = {}
}
export default ActionListeners