Last active
July 5, 2016 07:44
-
-
Save pocotan001/93885d4ac3ee1ac9d03515e314d65fa0 to your computer and use it in GitHub Desktop.
Higher-order component form of connectToStores
This file contains hidden or 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 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} /> | |
} | |
} | |
} |
This file contains hidden or 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 { 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