Created
July 11, 2017 19:37
-
-
Save hkjpotato/2729cbd016bad2ef6b421d13137cc7ce to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Subscription { | |
constructor(store, parentSub, onStateChange) { | |
this.store = store //global store from context | |
this.parentSub = parentSub //parentSub from context | |
this.onStateChange = onStateChange //its own listener | |
this.subscribed = false //a flag for testing whether itself has been subscribed | |
this.listeners = [] //nested subscription listeners subscribe here | |
} | |
//notify the listeners subscribed to itself | |
notifyNestedSubs() { | |
this.listeners.forEach(l=>l()); | |
} | |
trySubscribe() { | |
//if not yet subscribed | |
if (!this.subscribed) { | |
if (this.parentSub !== null) { | |
//if has parentSub(from context), subscribe to parentSub | |
this.parentSub.addNestedSub(this.onStateChange) | |
} | |
else { | |
//if root component, subscribe directly to store | |
this.store.subscribe(this.onStateChange) | |
} | |
//mark it as subscribed | |
this.subscribed = true; | |
} | |
} | |
//for adding nested subscription listener to itself | |
addNestedSub(listener) { | |
//FIRST, ensure itself has been subscribed, that's how the order is maintained | |
this.trySubscribe() | |
//THEN, subscribe the nested listener to its own listener collection | |
this.listeners.push(listener) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment