Created
May 10, 2015 09:42
-
-
Save nissoh/e835e940288b990d6160 to your computer and use it in GitHub Desktop.
Most & React - Stream ES7 decorator.
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
import React, { Component } from 'react'; | |
import excEnv from 'react/lib/ExecutionEnvironment'; | |
import most from 'most' | |
export default function Stream(streams) { | |
return DecoratedComponent => { | |
class StreamComponent extends Component { | |
constructor(props) { | |
super(props); | |
// ensure window object is defined so we can wire stream data | |
if (!excEnv.canUseDOM) { | |
return; | |
} | |
this.state = {...streams}; | |
this.stateCycle = most.create(add => { | |
this.stateCycleEnd = add; | |
}); | |
this.observe(streams); | |
} | |
componentWillUnmount() { | |
if (this.stateCycleEnd) { | |
this.stateCycleEnd(); | |
} | |
} | |
render() { | |
return <DecoratedComponent {...this.props} {...this.state} />; | |
} | |
observe(streamObj) { | |
for (let key in streamObj) { | |
if (!streamObj.hasOwnProperty(key)) { | |
return; | |
} | |
most.merge(this.stateCycle, streamObj[key]) | |
.until(this.stateCycle.take(1)) | |
.observe((x) => { | |
this.state[key] = x; | |
this.setState(this.state); | |
}); | |
} | |
} | |
} | |
return StreamComponent; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage