Created
July 9, 2017 14:05
-
-
Save ngryman/ac96e911abd78046e2f268efa91f3190 to your computer and use it in GitHub Desktop.
Router extensions
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 { Route, RouterEvents } from './router-exts' | |
const TrackScreen = html` | |
<section class="track-screen' | |
onenter=${() => console.log('enter track screen')} | |
onleave=${() => console.log('leave track screen')} | |
></section> | |
` | |
const HomeScreen = html` | |
<section class="track-screen' | |
onenter=${() => console.log('enter home screen')} | |
onleave=${() => console.log('leave home screen')} | |
></section> | |
` | |
app({ | |
view: [ | |
Route('/track', TrackScreen), | |
Route('*', HomeScreen) | |
], | |
mixins: [RouterEvents] | |
}) |
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
const routes = {} | |
let prevLocation = null | |
const process = (eventName, location, emit) => { | |
emit(`route:${eventName}`, location) | |
const root = routes[location.match] | |
const handler = root && root.data[`on${eventName}`] | |
if (handler) { | |
handler(location) | |
} | |
} | |
export const RouterEvents = (app) => ({ | |
events: { | |
route: (state, actions, location, emit) => { | |
if (prevLocation) { | |
process('leave', prevLocation, emit) | |
} | |
process('enter', location, emit) | |
prevLocation = location | |
} | |
} | |
}) | |
export const Route = (match, component) => { | |
const hoc = (state, actions) => { | |
const root = component(state, actions) | |
routes[match] = root | |
return root | |
} | |
return [match, hoc] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment