Skip to content

Instantly share code, notes, and snippets.

@benjick
Last active June 20, 2017 11:41
Show Gist options
  • Save benjick/21aad9c2953dcf3f385b589d62a3580b to your computer and use it in GitHub Desktop.
Save benjick/21aad9c2953dcf3f385b589d62a3580b to your computer and use it in GitHub Desktop.
mobx router
import Route from 'route-parser';
import {extendObservable, computed} from 'mobx';
class Router {
constructor(routes, notFound) {
extendObservable(this, {
routes: [],
currentPath: window.location.pathname,
notFound: null,
current: computed(() => this.computeCurrent()),
});
this.loadRoutes(routes, notFound);
}
computeCurrent() {
const found = this.routes.find(item => item.route.match(this.currentPath));
if (found) {
return {
component: found.component,
params: found.route.match(this.currentPath),
};
}
return {component: this.notFound};
}
loadRoutes(routes, notFound = null) {
this.routes = routes.map(route => ({
...route,
route: new Route(route.route),
}));
this.notFound = notFound;
}
go(url) {
if (url !== window.location.pathname) {
window.history.pushState({}, '', url);
}
this.currentPath = url;
}
}
export default Router;
import Router from './store/router';
import Counter from './Counter';
import TodoList from './TodoList';
import NotFound from './NotFound';
const routes = [
{
component: Counter,
route: '/',
},
{
component: TodoList,
route: '/todo/:todo',
},
];
const router = new Router(routes, NotFound);
export default router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment