Last active
August 29, 2015 14:15
-
-
Save kyle-ssg/e59a423d1b57c743168e to your computer and use it in GitHub Desktop.
BaseComponent for React with store listener handling
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
/** @jsx React.DOM */ | |
module.exports = function (options) { | |
return React.createClass( _.assign({}, options, { | |
_listeners: [], | |
listenTo: function (store, event, callback) { | |
this._listeners.push({ | |
store: store, | |
event: event, | |
callback: callback | |
}); | |
store.on(event, callback); | |
}, | |
componentWillUnmount: function () { | |
_.each(this._listeners, function (listener) { | |
listener.store.off(listener.event, listener.callback); | |
}); | |
return options.componentWillUnmount ? options.componentWillUnmount() : true; | |
} | |
})); | |
}; |
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
componentDidMount: function () { | |
this.listenTo(MessagesStore, 'change', this.onMessageStoreChange); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think you would want to implement this as a mixin
http://facebook.github.io/react/docs/reusable-components.html#mixins
that will be even shorter and you are assured that your componentWillUnmount will get called even if you use several mixins