Last active
August 29, 2015 14:15
-
-
Save gpbl/6cfb74e60b3f1429d7a5 to your computer and use it in GitHub Desktop.
EventListenerMixin for fluxible
This file contains 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
// 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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: