Skip to content

Instantly share code, notes, and snippets.

@hkjpotato
Created July 11, 2017 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hkjpotato/2729cbd016bad2ef6b421d13137cc7ce to your computer and use it in GitHub Desktop.
Save hkjpotato/2729cbd016bad2ef6b421d13137cc7ce to your computer and use it in GitHub Desktop.
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