封装hash

2019-08-15  本文已影响0人  不算程序员

封装

        // 创建了一个router的构造函数
        function Router() {
            // key用来存储hash  ,值代表该路径下的独立作用域
            this.routers = {};
            // 用来存储当前hash
            this.currentUrl = '';
        }

        // 接收hash以key\value形式存储到对象中,value为一个函数
        Router.prototype.route = function (path, callback) {
            this.routers[path] = callback || function () {};
        }

        // get hash用来执行对应函数
        Router.prototype.refresh = function () {
            this.currentUrl = window.location.hash.slice(1) || '/';
            this.routers[this.currentUrl]();
            // console.log(this.routers[this.currentUrl])
        }
        // 定义监听事件,初次页面加载所执行函数,及页面hash改变所执行的内容
        Router.prototype.init = function () {
            window.addEventListener('load', this.refresh.bind(this), false);
            window.addEventListener('hashchange', this.refresh.bind(this), false);
        }

        // 实例化
        var r = new Router();
        // 初始化
        r.init()

    
        });

用法

    r.route('/', function () {
            document.getElementById('app').style.background = 'red';
        });
        r.route('/index', function () {
            document.getElementById('app').style.background = 'orange';
        });
        r.route('/main', function () {
            document.getElementById('app').style.background = 'pink';
上一篇 下一篇

猜你喜欢

热点阅读