In my Pokemon application, I am using ES6, which does not support mixins. I noticed that I was using a lot of the same code repeatedly for interacting with my Reflux stores. I decided to set up a helper function for each of the stores, to make re-use of the same store in other components as DRY as possible.
In my helper class, I have three functions.
add(in_component){
// check for store key, and create if it doesn’t exist
(…)// check for the unsub key, and create if it doesn’t exist
(…)in_component.unsub.storeName = StoreComponent.listen(
this.listenToStore.bind(in_component)
)
}
remove(in_component){
in_component.unsub.storeName()
}
listenToStore(in_storeData){
const newState = _.clone(this.state)
newState.stores.storeName = in_storeData
this.setState(newState)
}
And then in any components I want to listen to the store, I import it, then call the add and remove functions accordingly:
componentDidMount(){
myStoreListenerClass.add(this)
}
componentWillUnmount(){
myStoreListenerClass.remove(this)
}