Skip to content

Instantly share code, notes, and snippets.

@itrelease
Forked from gaearon/ObservePolyfill.js
Last active August 29, 2015 14:17
Show Gist options
  • Save itrelease/565b6979b0c252ba1e88 to your computer and use it in GitHub Desktop.
Save itrelease/565b6979b0c252ba1e88 to your computer and use it in GitHub Desktop.
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