基于hashchange事件的JavaScript自定义路由实现

作者:微光时间:2026-10-22 01:02:26浏览:309

本文介绍如何使用JavaScript的hashchange事件实现自定义前端路由。通过封装Router类,结合addEventListener监听URL变化,并提供两种注册路由的方法:构造函数初始化与动态route方法。文章包含完整代码示例及注意事项,适合需要轻量级路由方案的前端开发者参考。

自定义路由实现概述

本文旨在实现一个自定义路由功能,核心在于利用浏览器提供的hashchange事件,并根据具体业务需求进行封装处理。

Router类构建与实例化

首先,需要构建一个名为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();
}

事件监听与this指向处理

在代码实现中,有一个关键点需要注意:在使用addEventListener添加事件监听时,必须正确处理this指向问题,通常需要使用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('body');
  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();
  }
  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';
  })
  </script>
 </body>
</html>
<script> 
</script>

以上即为本文的全部内容,希望这些内容能对您的学习或工作有所帮助,同时也欢迎大家继续支持本站!

作者最新文章