Skip to content
jlongyamPublic

About

A hash based router

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

60 Commits

Folders and files

Repository files navigation

Router

A hash based Router

npm version

But why?

The the difference of this router with other hash router is have ability to parse sub slash after query,

example

#page/test?asset=/path/to/file.js

That slash after querty parsed properly.

Features

  • simple -> focuc to hash only
  • small -> under 100 lines of code
  • query friedly -> explained above

Usage

Design site map

Import

import router from '@jlbyte/router'
  1. Basic design
console.dir( router.match('#index', ':page') );
{ path: 'index', params: { page: 'index' }, query: {} }
  1. Complex design
console.dir( router.match('#page/test?asset=path/to/file.js', 'page/:any') );
{
  path: 'page/test',
  params: { '$0': 'test' },
  query: { asset: 'path/to/file.js' }
}

See usage detail in usage/design.mjs

Test design

Example:

let hash = '#lib/test/src?path=./root/file.css'
let pattern = 'lib/:n/src' 
 

let result = { 
  path: 'lib/test/src',
  params: { n: 'test' },
  query: { path: './root/file.css' }
}

console.assert( router.match( hash, pattern ), result )
Create route

Design:

console.dir( router.match('#style/load?file=style.css', 'style/:action') )

Result:

{
  path: 'style/load',
  params: { action: 'load' },
  query: { file: 'style.css' }
}

Implementation:

router.route('style/:action', ({ params, query })=> {
  if(params.action === 'load') {
    console.log( query.file )
  }
})
Manage Navigation

Example:

router.navigate('#style/load?file=style.css')

See usage detail in usage/route.mjs

Pretty URL

How to create pretty URL like https://example.com/#/other/page

  1. Design first
console.log( 'Design', router.match('#/other', '/:page') );
  1. Catch route
router.route('/:page', ({params})=> {
  console.log('Routes: ', params);
}
  1. Test
router.navigate('#/other');

See usage/pretty.html for example

Summary
router.navigate('#page/anonymous'); // a.href="#page/anonymous
router.route('page/:which', ({params})=> {}); // params.which
router.handle(); // matched ? true : false

const routes = router.getRoute();
console.log(routes); // { arguments }

Similiar projects

Similiar project that using hash router

License

Distributed under the MIT License.

About

A hash based router

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages