SoFunction
Updated on 2025-04-10

JS implements custom routing

This article implements custom routing, mainly the use of event hashchange, and then encapsulates it according to our business needs.

First implement a router class and instantiate it.

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

The only thing you need to note above is that when using addEventListener, you need to pay attention to the use of bind function, because I fell into the trap and then I realized $.proxy().

When using the above, you can use two methods to register, but the second one depends on the first one.

Method 1:

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

Method 2:

('/3',function(){ = 'yellow'; })

Complete code:

<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 = ('body');
  function _router(config){
    = config ? config : {}; 
  } 
  _router.prototype = {
   event:function(str,callback){
    var events = (' ');
    for (var i in events) (events[i],callback,false);
   },
   init: function() {
    ('load hashchange',(this));
    return this;
   },
   refresh: function() {
     = (1) || '/';
    []();
   },
   route: function(path,callback){
    [path] = callback || function(){};
   }
  }
  function router (config){
   return new _router(config).init();
  }
  var Router = router({
   '/' : function(){ = 'white';},
   '/1': function(){ = 'blue';},
   '/2': function(){ = 'green';}
  })
  ('/3',function(){
    = 'yellow';
  })
  </script>
 </body>
</html>
<script> 
</script>

The above is all the content of this article. I hope that the content of this article will help you study or work. I also hope to support me more!