Last active
August 29, 2015 14:21
-
-
Save whatupdave/8adebb76ed4069a28fd0 to your computer and use it in GitHub Desktop.
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' | |
export default function connectToStores(...stores) { | |
return function(Component) { | |
return class StoreConnection extends React.Component { | |
constructor(props) { | |
super(props) | |
this.state = Component.getPropsFromStores() | |
this.handleStoresChanged = this.handleStoresChanged.bind(this) | |
} | |
render() { | |
return <Component {...this.props} {...this.state} />; | |
} | |
componentDidMount() { | |
stores.forEach(store => | |
store.addChangeListener(this.handleStoresChanged) | |
); | |
} | |
componentWillUnmount() { | |
stores.forEach(store => | |
store.removeChangeListener(this.handleStoresChanged) | |
); | |
} | |
handleStoresChanged() { | |
this.setState(Component.getPropsFromStores()) | |
} | |
} | |
} | |
} |
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
@connectToStores(ChangelogStore, SessionStore) | |
export default class ApplicationNavbar extends React.Component { | |
static getPropsFromStores() { | |
return { | |
user: SessionStore.user, | |
changelog: ChangelogStore.changelog | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment