首頁  >  文章  >  web前端  >  js實作自訂路由

js實作自訂路由

高洛峰
高洛峰原創
2017-02-06 11:11:11994瀏覽

本文實作自訂路由,主要是事件hashchange的使用,然後根據我們的業務需求封裝。

先實作一個router的類,並且實例化。

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的時候,需要注意bind函數的使用,因為我是踩了坑,這才體會到$.proxy()。

上邊使用的時候可以使用兩種方法進行註冊,但第二種是依賴第一種的。

方法一:

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

方法二:

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>

reee全部內容,希望本文的內容對大家的學習或工作能帶來一定的幫助,同時也希望多多支持PHP中文網!

更多js實作自訂路由相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn