>  기사  >  웹 프론트엔드  >  js는 사용자 정의 라우팅을 구현합니다.

js는 사용자 정의 라우팅을 구현합니다.

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

이 문서에서는 주로 이벤트 해시 변경을 사용하여 사용자 정의 라우팅을 구현한 다음 비즈니스 요구 사항에 따라 이를 캡슐화합니다.

먼저 라우터 클래스를 구현하고 인스턴스화합니다.

function _router(config){
 this.config = config ? config : {}; 
} 
_router.prototype = {
 event:function(str,callback){
  var events = str.split(' ');
  for (var i in events) window.addEventListener(events[i],callback,false);
 },
init: function() {
 this.event('load hashchange',this.refresh.bind(this));
 return this;
},
refresh: function() {
 this.currentUrl = location.hash.slice(1) || '/';
 this.config[this.currentUrl]();
},
route: function(path,callback){
 this.config[path] = callback || function(){};
}
}
function router (config){
 return new _router(config).init();
}

위에서 주의할 점은 addEventListener를 사용할 때 트랩을 밟고 $.proxy()를 깨달았기 때문에 바인드 기능의 사용에 주의해야 한다는 점이다.

위에서 사용할 때 두 가지 방법으로 등록할 수 있는데, 두 번째 방법은 첫 번째 방법에 따라 다릅니다.

방법 1:

var Router = router({
 '/' : function(){content.style.backgroundColor = 'white';},
 '/1': function(){content.style.backgroundColor = 'blue';},
 '/2': function(){content.style.backgroundColor = 'green';}
})

방법 2:

Router.route('/3',function(){ content.style.BackgroundColor = 'yellow'; })

전체 코드:

<html>
 <head>
  <title></title>
 </head>
 <body>
  <ul>
   <li><a href="#/1">/1: blue</a></li>
   <li><a href="#/2">/2: green</a></li>
   <li><a href="#/3">/3: yellow</a></li>
  </ul>
  <script>
  var content = document.querySelector(&#39;body&#39;);
  function _router(config){
   this.config = config ? config : {}; 
  } 
  _router.prototype = {
   event:function(str,callback){
    var events = str.split(&#39; &#39;);
    for (var i in events) window.addEventListener(events[i],callback,false);
   },
   init: function() {
    this.event(&#39;load hashchange&#39;,this.refresh.bind(this));
    return this;
   },
   refresh: function() {
    this.currentUrl = location.hash.slice(1) || &#39;/&#39;;
    this.config[this.currentUrl]();
   },
   route: function(path,callback){
    this.config[path] = callback || function(){};
   }
  }
  function router (config){
   return new _router(config).init();
  }
  var Router = router({
   &#39;/&#39; : function(){content.style.backgroundColor = &#39;white&#39;;},
   &#39;/1&#39;: function(){content.style.backgroundColor = &#39;blue&#39;;},
   &#39;/2&#39;: function(){content.style.backgroundColor = &#39;green&#39;;}
  })
  Router.route(&#39;/3&#39;,function(){
   content.style.backgroundColor = &#39;yellow&#39;;
  })
  </script>
 </body>
</html>
<script> 
</script>

위 내용은 이 글의 전체 내용입니다. 이 글의 내용이 모든 분들의 공부나 업무에 조금이라도 도움이 되었으면 좋겠습니다. PHP 중국어 웹사이트!

JS의 사용자 정의 라우팅 구현과 관련된 더 많은 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!

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