Created
May 5, 2015 15:57
-
-
Save vslinko/6afc275f8f60ecd76663 to your computer and use it in GitHub Desktop.
higher order component example
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
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