Created
March 1, 2017 20:24
-
-
Save danieldunderfelt/4d016333a947764c1a5687d26d48ca27 to your computer and use it in GitHub Desktop.
Simple hash router
This file contains hidden or 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
/** | |
* Simple router for switching between hash stings. | |
* Suitable for MobX/Redux architecture and especially | |
* handy for tabs, which is the reason why it exists. | |
const state = { currentTab: 'lions' } | |
function activateTab(tabName) { | |
// Dispatch state change | |
state.currentTab = tabName | |
} | |
// Instantiate a router and set the index route | |
// which is what get() will return when the hash is empty. | |
const router = hashrouter('lions') | |
router.listen(activateTab) | |
<TabBar | |
tabs={[ | |
{ name: 'lions', label: 'Lions' }, | |
{ name: 'tigers', label: 'Tigers' } | |
]} | |
onSelect={ tab => router.go(tab.name) } | |
selectedTab={ state.currentTab } /> | |
**/ | |
const listeners = [] | |
export default index => { | |
function go(toRoute) { | |
window.location.hash = toRoute | |
notifyListeners() | |
return get() | |
} | |
function get() { | |
const current = window.location.hash.slice(1) | |
return current.length > 0 ? current : index | |
} | |
function isActive(route) { | |
return get() === route | |
} | |
function listen(listener) { | |
listeners.push(listener) | |
} | |
function notifyListeners() { | |
const cur = get() | |
listeners.forEach(listener => listener(cur)) | |
} | |
window.onhashchange = notifyListeners | |
return { | |
go, | |
get, | |
isActive, | |
listen | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment