forked from reduxjs/react-redux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubscription.js
56 lines (46 loc) · 1.29 KB
/
Subscription.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
// enapsulates the subscription logic for connecting a component to the redux store, as well as
// nesting subscriptions of decendant components, so that we can ensure the ancestor components
// re-render before descendants
export default class Subscription {
constructor(store, parentSub, onStateChange) {
this.subscribe = parentSub
? parentSub.addNestedSub.bind(parentSub)
: store.subscribe
this.onStateChange = onStateChange
this.lastNestedSubId = 0
this.unsubscribe = null
this.nestedSubs = {}
this.notifyNestedSubs = this.notifyNestedSubs.bind(this)
}
addNestedSub(listener) {
this.trySubscribe()
const id = this.lastNestedSubId++
this.nestedSubs[id] = listener
return () => {
if (this.nestedSubs[id]) {
delete this.nestedSubs[id]
}
}
}
isSubscribed() {
return Boolean(this.unsubscribe)
}
notifyNestedSubs() {
const keys = Object.keys(this.nestedSubs)
for (let i = 0; i < keys.length; i++) {
this.nestedSubs[keys[i]]()
}
}
trySubscribe() {
if (this.unsubscribe) return
this.unsubscribe = this.subscribe(() => {
this.onStateChange(this.notifyNestedSubs)
})
}
tryUnsubscribe() {
if (this.unsubscribe) {
this.unsubscribe()
}
this.unsubscribe = null
}
}