>  기사  >  웹 프론트엔드  >  JS에서 간단한 라우터 기능을 구현하는 방법

JS에서 간단한 라우터 기능을 구현하는 방법

高洛峰
高洛峰원래의
2017-02-06 11:57:181960검색

이 글의 예시에서는 JS에서 간단한 라우터 기능을 구현하는 방법을 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요. 구체적인 구현 방법은 다음과 같습니다.

var wawa = {};
wawa.Router = function(){
  function Router(){
  }
  Router.prototype.setup = function(routemap, defaultFunc){
    var that = this, rule, func;
    this.routemap = [];
    this.defaultFunc = defaultFunc;
    for (var rule in routemap) {
      if (!routemap.hasOwnProperty(rule)) continue;
      that.routemap.push({
        rule: new RegExp(rule, 'i'),
        func: routemap[rule]
      });       
    }
  };
  Router.prototype.start = function(){
    console.log(window.location.hash);
    var hash = location.hash, route, matchResult;
    for (var routeIndex in this.routemap){
      route = this.routemap[routeIndex];
      matchResult = hash.match(route.rule);
      if (matchResult){
        route.func.apply(window, matchResult.slice(1));
        return; 
      }
    }
    this.defaultFunc();
  };
  return Router;
}();
var router = new wawa.Router();
router.setup({
  '#/list/(.*)/(.*)': function(cate, id){
      console.log('list', cate, id);
    },
  '#/show/(.*)': function(id){
      console.log('show', id); 
    }
}, function(){
  console.log('default router');
});
router.start();

이 글이 모든 분들의 자바스크립트 프로그래밍 설계에 도움이 되기를 바랍니다.

간단한 라우터 기능을 구현하는 JS 메소드와 관련된 더 많은 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.