Skip to content

Instantly share code, notes, and snippets.

@vslinko
Created May 5, 2015 15:57
Show Gist options
  • Save vslinko/6afc275f8f60ecd76663 to your computer and use it in GitHub Desktop.
Save vslinko/6afc275f8f60ecd76663 to your computer and use it in GitHub Desktop.
higher order component example
import React from 'react';
const mounted = {};
const listeners = {};
function startListener(eventName) {
if (!listeners[eventName]) {
listeners[eventName] = (event) => {
mounted[eventName].forEach(([c, cb]) => cb(c.child, event));
};
document.addEventListener(eventName, listeners[eventName]);
}
}
function stopListener(eventName) {
document.removeEventListener(eventName, listeners[eventName]);
listeners[eventName] = null;
}
export default function onDocumentEvent(spec) {
return Component => {
return class DocumentEventsComponent extends React.Component {
componentDidMount() {
Object.keys(spec).forEach(eventName => {
if (!mounted[eventName]) {
mounted[eventName] = [];
}
mounted[eventName].push([this, spec[eventName]]);
startListener(eventName);
});
}
componentWillUnmount() {
Object.keys(spec).forEach(eventName => {
mounted[eventName] = mounted[eventName].filter(([c]) => c !== this);
if (mounted[eventName].length === 0) {
stopListener();
}
});
}
render() {
return <Component {...this.props} ref={c => this.child = c} />;
}
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment