hash-routers
v1.0.3
Published
frontend router base on `window.location.hash`
Downloads
3
Readme
Router
:hash: frontend router base on window.location.hash
Installation
with webpack
npm install hash-routers
simple script
<script src="./src/Router.js"></script>
Documents
base
import Router from 'hash-routers'
// const Router = require('hash-routers')
// const Router = window.Router
let router = new Router()
router.addRoute('/index', function () {
// ...
})
router.addRoute('/list', function () {
// ...
})
pipeline
router.addRoute('/index', function () {
// ...
}).addRoute('/list', function () {
// ...
})
multiple path handler
router.addRoute('/index', '/404', function () {
// ...
})
router.addRoute(['/index', '/404'], function () {
// ...
})
path params
router.addRoute('/detail/:id', function (event) {
console.log(event.params) // { id: x }
})
multiple handler
You can exec event.preventDefault()
to terminate the execution below
router.addRoute('/index', function (event) {
event.preventDefault()
}).addRoute('/index', function (params) {
// can not be call
})
data relay
Get data from event.datas
router.addRoute('/index', function () {
return 1
}).addRoute('/index', function () {
return {
name: 'Niko'
}
}).addRoute('/index', function () {
}).addRoute('/index', function (event) {
console.log(event.datas)
// [1, { name: 'Niko' }, undefined]
})
async supports
router.addRoute('/index', async function () {
let result = await somePromise
return result
}).addRoute('/index', function (event) {
console.log(`get data: ${event.datas[0]}`)
})
remove handlers
seem syntax like addRoute
let handler = function () {
// just call on page2
}
router.addRoute(['/page1', '/page2', '/page3'], handler)
router.removeRoute('/page1', '/page3', handler)
redirect
router.addRoute('/page1', function () {
})
router.redirect('/page1')
redirect with params
router.addRoute('/user/:uid', function (event) {
console.log(`got data: ${event.params}`) // got data: { uid: 1 }
})
router.redirect('/user/:uid', {
uid: 1
})
unknown handler
router.unknown(function (path) {
console.log(`unknown path: ${path}`)
})
TODO
~~Programming~~
~~yes... it's just a document for now~~
Test case