Skip to content

Instantly share code, notes, and snippets.

@nissoh
Created May 10, 2015 09:42
Show Gist options
  • Save nissoh/e835e940288b990d6160 to your computer and use it in GitHub Desktop.
Save nissoh/e835e940288b990d6160 to your computer and use it in GitHub Desktop.
Most & React - Stream ES7 decorator.
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;
}
}
@nissoh
Copy link
Author

nissoh commented May 10, 2015

Usage

@Stream({
  todos: todosCursor.stream
})
class Todos extends React.Component {}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment