Last active
June 20, 2017 11:41
-
-
Save benjick/21aad9c2953dcf3f385b589d62a3580b to your computer and use it in GitHub Desktop.
mobx router
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 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; |
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 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