Skip to content

Instantly share code, notes, and snippets.

@gpbl
Last active August 29, 2015 14:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gpbl/6cfb74e60b3f1429d7a5 to your computer and use it in GitHub Desktop.
Save gpbl/6cfb74e60b3f1429d7a5 to your computer and use it in GitHub Desktop.
EventListenerMixin for fluxible
// Add a listenTo() method to listen to a specific store event (see comment for an example)
const EventListenerMixin = {
componentDidMount() {
this._storeEventListeners = [];
},
listenTo(store, eventName, handler) {
if (!handler) {
let handlerName = 'on' + eventName.charAt(0).toUpperCase() + eventName.slice(1);
handler = this[handlerName];
}
if(!handler)
throw new Error(`listenTo attempted to add undefined handler for ${eventName}. Make sure handlers are actually exist.`);
this._attachStoreEventListener({
store: store,
eventName: eventName,
handler: handler
});
},
_attachStoreEventListener(listener) {
if (this.isMounted && !this.isMounted())
throw new Error('StoreListenerMixin called listenTo when component wasn\'t mounted.');
listener.store.addListener(listener.eventName, listener.handler);
this._storeEventListeners.push(listener);
},
componentWillUnmount() {
this._storeEventListeners.forEach((listener) => {
listener.store.removeListener(listener.eventName, listener.handler);
});
this._storeEventListeners = [];
}
};
export default EventListenerMixin;
@gpbl
Copy link
Author

gpbl commented Feb 21, 2015

Example:

const MyComponent = React.createClass({
  mixins: [EventListenerMixin],

  componentDidMount() {
    this.listenTo(this.getStore(MyStore), 'loadSuccess'); // handler will be `onLoadSuccess()`
    this.listenTo(this.getStore(MyStore), 'loadFailure', this.handleLoadFailure); // explicit handler
  },

  componentWillUnmount() {
    // the mixin will remove listeners for you
  },

  onLoadSuccess(payload) {
   console.log('loaded', payload);  
  },

  handleLoadFailure(err) {
    alert(err.message)
  },


});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment