Skip to content

Instantly share code, notes, and snippets.

@kyle-ssg
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 kyle-ssg/e59a423d1b57c743168e to your computer and use it in GitHub Desktop.
Save kyle-ssg/e59a423d1b57c743168e to your computer and use it in GitHub Desktop.
BaseComponent for React with store listener handling
/** @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;
}
}));
};
componentDidMount: function () {
this.listenTo(MessagesStore, 'change', this.onMessageStoreChange);
}
@crucialfelix
Copy link

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

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