ホームページ  >  記事  >  ウェブフロントエンド  >  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() に気づいたためです。

上記で使用する場合、2 つの方法で登録できますが、2 番目の方法は最初の方法に依存します。

方法 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 中国語 Web サイトもサポートしたいと思っています。

カスタム ルーティングの js 実装に関連するその他の記事については、PHP 中国語 Web サイトに注目してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。