Skip to content

Instantly share code, notes, and snippets.

@solomonhawk
Last active August 29, 2015 14:16
Show Gist options
  • Save solomonhawk/6fff8eedb8d23ef4414f to your computer and use it in GitHub Desktop.
Save solomonhawk/6fff8eedb8d23ef4414f to your computer and use it in GitHub Desktop.
EZ Store Listening
// some pieces of this file have been omitted
let React = require('react')
let notesStore = require('../../stores/notesStore')
let monitorMixin = require('../../mixins/monitorMixin')
let Notes = React.createClass({
mixins: [monitorMixin(notesStore)]
// this gets called whenever `notesStore` emits a change event
getState() {
return notesStore.getState().notes
},
getInitialState() {
return this.getState()
},
render() {
return (
<div>
<h3> Notes for { this.props.username } </h3>
<AddNote username={ this.props.username } />
<NotesList notes={ this.state.notes } />
</div>
)
}
})
module.exports = Notes
// monitorMixin expects the component that mixes it in to implement a `getState()`
// function which grabs state from the store and returns just what this component cares about
module.exports = (store) => {
return {
componentDidMount() {
store.addChangeListener(this._onChange)
},
componentWillUnmount() {
store.removeChangeListener(this._onChange)
},
_onChange() {
this.setState(this.getState())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment