zoukankan      html  css  js  c++  java
  • js 实现路由功能

    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

  • 相关阅读:
    二叉查找树
    Hash算法原理理解
    算法的时间复杂度
    解决Ubuntu14.04下Clementine音乐播放器不能播放wma文件的问题
    Ubuntu 14.04 开启启动器图标最小化功能
    Ubuntu14.04建立WiFi热点
    C语言运算符优先级
    老鸟的Python入门教程
    MD5算法步骤详解
    MD5算法
  • 原文地址:https://www.cnblogs.com/honghong87/p/9291278.html
Copyright © 2011-2022 走看看