Maison  >  Article  >  interface Web  >  js implémente un routage personnalisé

js implémente un routage personnalisé

高洛峰
高洛峰original
2017-02-06 11:11:11994parcourir

Cet article implémente un routage personnalisé, principalement en utilisant le hachage d'événement, puis l'encapsule en fonction de nos besoins commerciaux.

Implémentez d’abord une classe de routeur et instanciez-la.

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();
}

La seule chose qui doit être notée ci-dessus est que lorsque vous utilisez addEventListener, vous devez faire attention à l'utilisation de la fonction bind, car j'ai marché sur un piège et j'ai ensuite réalisé $.proxy( ).

Vous pouvez utiliser deux méthodes pour vous inscrire lorsque vous l'utilisez ci-dessus, mais la seconde dépend de la première.

Première méthode :

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

Méthode deux :

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

Code complet :

<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>

Ce qui précède est l'intégralité du contenu de cet article. J'espère que le contenu de cet article pourra être utile aux études ou au travail de chacun, et j'espère aussi. pour supporter davantage le site Web chinois !

Pour plus d'articles liés à l'implémentation js du routage personnalisé, veuillez faire attention au site Web PHP chinois !

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn