This repository has been archived by the owner on Dec 19, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
Named States
Casey Webb edited this page Dec 18, 2016
·
3 revisions
import Router from 'ko-component-router'
import pathToRegexp from 'path-to-regexp'
const states = {
'user': {
path: '/user',
component: 'user-index',
states: {
'list': {
path: '/',
component: 'user-list'
},
'create': {
path: '/new',
component: 'user-create'
},
'show': {
path: '/:id',
component: 'user-show'
},
'edit': {
path: '/:id/edit',
component: 'user-edit'
},
}
}
}
function toRoutes(states) {
return Object.entries(states).reduce((routes, [stateName, { path, component, states }]) => {
routes[path] = []
if (component) routes[path].push(component)
if (states) routes[path].push(toRoutes(states))
return routes
}, {})
}
function navigateToState(state, params, push = true) {
let path = ''
let _states = states
for (const _state of state.split('.')) {
path += _states[_state].path
_states = _states[_state].states
}
path = pathToRegexp.compile(path)(params)
return Router.update(path, push)
}
Router.routes = toRoutes(states)
Router.navigateToState = navigateToState
// Router.navigateToState('user.edit', { id: user.id })