码迷,mamicode.com
首页 > Web开发 > 详细

js 实现路由功能

时间:2018-07-10 21:37:09      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:router   else   att   struct   ams   exp   otf   功能   []   

class Router {
  constructor() {
    this.routes = []
  }
  handle(pattern, handler) {
    this.routes.push({ pattern, handler })
  }
  exec(pathname) {
    for (const route of this.routes) {
      if (typeof route.pattern === ‘string‘) {
        if (route.pattern === pathname) {
          return route.handler()
        }
      } else if (route.pattern instanceof RegExp) {
        const result = pathname.match(route.pattern)
        if (result !== null) {
          const params = result.slice(1).map(decodeURIComponent)
          return route.handler(...params)
        }
      }
    }
  }
}
const router = new Router()
router.handle(‘/‘, homePage)
router.handle(/^\/users\/([^\/]+)$/, userPage)
router.handle(/^\//, notFoundPage)
function homePage() {
  return ‘home page‘
}
function userPage(username) {
  return `${username}‘s page`
}
function notFoundPage() {
  return ‘not found page‘
}
console.log(router.exec(‘/‘)) // home page
console.log(router.exec(‘/users/john‘)) // john‘s page
console.log(router.exec(‘/foo‘)) // not found page

js 实现路由功能

标签:router   else   att   struct   ams   exp   otf   功能   []   

原文地址:https://www.cnblogs.com/honghong87/p/9291278.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!