Created
March 15, 2015 19:31
-
-
Save gaearon/7d94c9f38fdd34a6e690 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
export default { | |
getInitialState() { | |
const data = {}; | |
this.subscribe(this.props, this.context, (key, value) => { | |
data[key] = value; | |
}); | |
this.unsubscribe(); | |
return { data }; | |
}, | |
componentWillMount() { | |
this.subscribe(this.props, this.context, this.setData); | |
}, | |
componentWillReceiveProps(props, context) { | |
this.subscribe(props, context, this.setData); | |
}, | |
componentWillUnmount() { | |
this.unsubscribe(); | |
}, | |
setData(key, value) { | |
this.setState({ | |
data: {...this.state.data, [key]: value } | |
}); | |
}, | |
subscribe(props, context, onNext) { | |
const newObservables = this.observe(props, context); | |
const newSubscriptions = {}; | |
for (let key in newObservables) { | |
newSubscriptions[key] = newObservables[key].subscribe({ | |
onNext: (value) => onNext(key, value), | |
onError: () => {}, | |
onCompleted: () => {} | |
}); | |
} | |
this.unsubscribe(); | |
this.subscriptions = newSubscriptions; | |
}, | |
unsubscribe() { | |
for (let key in this.subscriptions) { | |
if (this.subscriptions.hasOwnProperty(key)) { | |
this.subscriptions[key].dispose(); | |
} | |
} | |
this.subscriptions = {}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Found a small bug/implementation detail. When a component unsubscribes, the old data is not purged.
This is easy to fix by adding this code at the end of the subscribe method:
This will purge the data for keys that no longer have a subscription.