forked from reduxjs/react-redux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubscription.js
58 lines (48 loc) · 1.37 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
57
58
// encapsulates 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.unsubscribe = null
this.nestedSubs = []
this.notifyNestedSubs = this.notifyNestedSubs.bind(this)
}
addNestedSub(listener) {
this.trySubscribe()
this.nestedSubs = this.nestedSubs.concat(listener)
let subscribed = true
return () => {
if (!subscribed) return
subscribed = false
const subs = this.nestedSubs.slice()
const index = subs.indexOf(listener)
subs.splice(index, 1)
this.nestedSubs = subs
}
}
isSubscribed() {
return Boolean(this.unsubscribe)
}
notifyNestedSubs() {
const subs = this.nestedSubs
for (let i = subs.length - 1; i >= 0; i--) {
subs[i]()
}
}
trySubscribe() {
if (this.unsubscribe) return
this.unsubscribe = this.subscribe(() => {
this.onStateChange(this.notifyNestedSubs)
})
}
tryUnsubscribe() {
if (this.unsubscribe) {
this.unsubscribe()
}
this.unsubscribe = null
}
}