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

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

HTML代码

<section>
    <ul>
        <li><a href="#/">全部</a></li>
        <li><a href="#/html">html课程</a></li>
        <li><a href="#/css">css课程</a></li>
        <li><a href="#/javascript">javascript课程</a></li>
    </ul>
</section>

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方法。所以会报以上错误;
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 请参看我github中的wiki,不定期更新。https://github.com/ivonzhang/Front...
    zhangivon阅读 7,212评论 2 19
  • 在线阅读 http://interview.poetries.top[http://interview.poetr...
    前端进阶之旅阅读 114,926评论 24 450
  • 链接在此就是一道思维题,通过分析题得知,每个瓶子可以装2^x这么多水,即这么多的水可以装在一个瓶子里,所以: 每2...
    Anxdada阅读 337评论 0 0
  • 自从听了潍坊市清平小学武际金校长“家校合育”的报告,近几天大脑中一直在思考着这个问题。 ”家校合育”...
    辙穷其趣阅读 280评论 0 3
  • 我有时候会自己写几个字,类似日记的那种,别的没写过。上个月看到有这个训练营就动过心思。这个月终于参加。只是,真的写...
    薇Wei花开阅读 156评论 3 2