hash实现前端路由实例及addEventListener事件监听里回调函数的this指向问题

前端路由的核心原理是更新页面但不向服务器发起请求,目前在浏览器环境中这一功能的实现主要有两种方式:

  • 利用URL中的hash(“#”)
  • 利用HTML5新增的方法History interface
    参考:js单页hash路由原理与应用实战 里的

HTML代码

js代码

    class Router{
        constructor(){
            this.routs={};
            this.curURL = '';
        }
        //监听路由变化
        init(){
            console.log(this);
            window.addEventListener("hashchange", this.reloadPage);
        }
        //获取路由参数
        reloadPage(){
            console.log(this);
            this.curURL = location.hash.substring(1) || "/";
            this.routs[this.curURL]();
        }

       //保存路由对应的函数
        map(key,callback){
            this.routs[key] = callback;
        }
   }

   const iRouter = new Router();
   iRouter.map("/", ()=>{
       let oSidebar = document.querySelector("sidebar");
       oSidebar.innerHTML = 'html,css,javascript';
   })
   iRouter.map("/html",()=>{
       let oSidebar = document.querySelector("sidebar");
       oSidebar.innerHTML = 'html5';
   })
   iRouter.map("/css",()=>{
       let oSidebar = document.querySelector("sidebar");
       oSidebar.innerHTML = 'css';
   })
   iRouter.map("/javascript",()=>{
       let oSidebar = document.querySelector("sidebar");
       oSidebar.innerHTML = 'javascript';
   })
   iRouter.init();

window.addEventLister("hashchange",this.reloadPage.bind(this))

对于本渣这行代码有几个要学习知识点

  1. 当 一个窗口的哈希改变时就会触发 hashchange 事件。即URL由“index.html#/”变为“index.html#/css”时,执行reloadPage方法。
  2. 为什么使用bind, MDN关于this的文档里写到“函数被用作DOM事件处理函数时,它的this指向触发事件的元素”。这里不绑定this的话,执行时this就是window对象。
  3. bug解决,当不绑定this时点击导航会报错:Uncaught TypeError: Cannot read property '/css' of undefined at reloadPage ;控制台查看js 错误提示停留在this.routs[this.curURL](); this.reloadPage相当于window.reloadPage。window上临时生成了一个空的reloadPage方法。所以会报以上错误;

你可能感兴趣的:(hash实现前端路由实例及addEventListener事件监听里回调函数的this指向问题)