Skip to content

Instantly share code, notes, and snippets.

@pocotan001
Last active July 5, 2016 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pocotan001/93885d4ac3ee1ac9d03515e314d65fa0 to your computer and use it in GitHub Desktop.
Save pocotan001/93885d4ac3ee1ac9d03515e314d65fa0 to your computer and use it in GitHub Desktop.
Higher-order component form of connectToStores
import React from 'react'
/**
* Higher-order component form of connectToStores
*
* @param {ReactElement} Component
* @param {Store[]} stores
* @param {Object} getStateFromStores
* @returns {ReactElement} StoreConnection
*/
export default function connectToStores (Component, stores, getStateFromStores) {
return class StoreConnection extends React.Component {
state = getStateFromStores(this.props)
onChange = () => {
this.setState(getStateFromStores(this.props))
}
componentDidMount () {
stores.forEach((store) => store.addChangeListener(this.onChange))
}
componentWillUnmount () {
stores.forEach((store) => store.removeChangeListener(this.onChange))
}
render () {
return <Component {...this.props} {...this.state} />
}
}
}
import { EventEmitter } from 'events'
import Dispatcher from '../Dispatcher'
const CHANGE_EVENT = 'change'
/**
* Extend certain stores from a this `Store` class
*/
export default class Store extends EventEmitter {
emitChange () {
this.emit(CHANGE_EVENT)
}
addChangeListener (listener) {
this.addListener(CHANGE_EVENT, listener)
}
removeChangeListener (listener) {
this.removeListener(CHANGE_EVENT, listener)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment