Skip to content

Instantly share code, notes, and snippets.

@tusharmath
Created July 25, 2016 14:31
Show Gist options
  • Save tusharmath/fc739c573defeb672b2e33c307cfbdb0 to your computer and use it in GitHub Desktop.
Save tusharmath/fc739c573defeb672b2e33c307cfbdb0 to your computer and use it in GitHub Desktop.
Base class to make your component work with Rx
import {Subject} from 'rx'
import {Component} from 'react'
import R from 'ramda'
const appendPrefix = (x) => ['@PROPS.' + x[0], x[1]]
const propPair = R.compose(R.map(appendPrefix), R.toPairs)
export class SmartyPants extends Component {
constructor () {
super()
const __subject = this.__subject = new Subject()
this.fromCB = R.curry((name, value) => __subject.onNext([name, value]))
this.select = (name) => __subject.filter((x) => x[0] === name).map((x) => x[1])
this.__dispatchProps = () => R.forEach(__subject.onNext.bind(__subject), propPair(this.props))
const _render = this.render
this.render = () => _render(R.pickAll(['state', 'fromCB'], this))
}
componentWillReceiveProps (nextProps) {
this.__dispatchProps(nextProps)
}
shouldComponentUpdate (_, nextState) {
return this.state !== nextState
}
componentWillMount () {
const props = this.props
if (this.init) {
const {intent$, state$} = this.init.call(null, R.pickAll(['select'], this))
if (state$) this.__disposable = state$.subscribe((state) => this.setState(state))
if (props.onIntent && intent$) props.onIntent(intent$)
this.__dispatchProps(this.props)
}
}
componentWillUnMount () {
if (this.__subject) this.__subject.onCompleted()
if (this.__disposable) this.__disposable.dispose()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment